Convert a string all caps or all small in JavaScript
This post will discuss how to convert a string all caps or all small in JavaScript.
There are several methods to convert a string all caps or all small in JavaScript. Here are some of the most common functions:
1. Using toUpperCase() and toLowerCase() function
We can use the toUpperCase() and toLowerCase() functions of the string object, which return a new string with all the characters converted to upper or lower case respectively. We can use these functions to convert a string by calling them on the string value. These methods do not change the original string. For example, we can convert a string to uppercase using toUpperCase() and lowercase using toLowerCase() like this:
|
1 2 3 4 5 6 7 |
let str = "Hello, World!"; let upperStr = str.toUpperCase(); console.log(upperStr); // "HELLO, WORLD!" let lowerStr = str.toLowerCase(); console.log(lowerStr); // "hello, world!" |
2. Using replace() function
Another way is to use the replace() function, which is a built-in function of the string object. It accepts a regular expression and a replacement string as arguments and gives us a new string that is the result of changing the matches of the regular expression with the replacement string. We can use a regular expression that matches any character in the string, such as /./g, and change it with its uppercase or lowercase version using the toUpperCase() or the toLowerCase() function. For instance, we can make a string uppercase and lowercase using replace() like this:
|
1 2 3 4 5 6 7 |
let str = "Hello, World!"; let upperStr = str.replace(/./g, c => c.toUpperCase()); console.log(upperStr); // "HELLO, WORLD!" let lowerStr = str.replace(/./g, c => c.toLowerCase()); console.log(lowerStr); // "hello, world!" |
That’s all about converting a string all caps or all small in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)