Invert case of a string in JavaScript
This post will discuss how to invert case of a string in JavaScript.
To invert the case of a string in JavaScript, we can use the following approaches:
1. Using a loop
One way is to loop through the string using a for…of loop and for each character, check if it’s in uppercase. If it is, reverse it to lowercase, and if it’s lowercase, make it uppercase. We can use the toUpperCase() and toLowerCase() functions to convert the character cases. For example, if we have a string, we can invert its case using a for loop like this:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
let str = "Hello, world!"; let newStr = ""; for (let char of str) { let upper = char.toUpperCase(); if (char === upper) { newStr += char.toLowerCase(); } else { newStr += upper; } } // "hELLO, WORLD!" console.log(newStr); |
2. Using replace() function
Another way is to use the replace() function with a regular expression and a callback function. This function will search for all alphanumeric characters in the string using the regular expression /[A-Za-z]/g, and replace them with their opposite case using the callback function. The callback function will take each matched character as an argument, and return its opposite case using the same functions as before. For example, using the same string as before, we can invert its case using replace() like this:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
let str = "Hello, world!"; let newStr = str.replace(/[A-Za-z]/g, function(char) { let upper = char.toUpperCase(); if (char === upper) { return char.toLowerCase(); } else { return upper; } }); // "hELLO, WORLD!" console.log(newStr); |
3. Using split() and map() function
A third way is to use the split() function with the map() function of the array object. This function will first split the string into an array of single-character strings, using an empty string as the separator. Then it will map each element of the array to its opposite case using a callback function that has the same logic as before. Finally, it will join the array elements back into a string using an empty string as the separator. For example, using the same string as before, we can invert its case using split() and map() like this:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
let str = "Hello, world!"; let newStr = str.split("").map(function(char) { let upper = char.toUpperCase(); if (char === upper) { return char.toLowerCase(); } else { return upper; } }).join(""); // "hELLO, WORLD!" console.log(newStr); |
That’s all about inverting case of a string 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 :)