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:

Download  Run Code

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:

Download  Run Code

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:

Download  Run Code

That’s all about inverting case of a string in JavaScript.