Swap Case on javascript

Solution 1:

Like Ian said, you need to build a new string.

var swapCase = function(letters){
    var newLetters = "";
    for(var i = 0; i<letters.length; i++){
        if(letters[i] === letters[i].toLowerCase()){
            newLetters += letters[i].toUpperCase();
        }else {
            newLetters += letters[i].toLowerCase();
        }
    }
    console.log(newLetters);
    return newLetters;
}

var text = 'So, today we have REALLY good day';

var swappedText = swapCase(text); // "sO, TODAY WE HAVE really GOOD DAY"

Solution 2:

You can use this simple solution.

var text = 'So, today we have REALLY good day';

var ans = text.split('').map(function(c){
  return c === c.toUpperCase()
  ? c.toLowerCase()
  : c.toUpperCase()
}).join('')

console.log(ans)

Using ES6

var text = 'So, today we have REALLY good day';

var ans = text.split('')
.map((c) =>
 c === c.toUpperCase() 
 ? c.toLowerCase()
 : c.toUpperCase()
).join('')

console.log(ans)

Solution 3:

guys! Get a little simplier code:

string.replace(/\w{1}/g, function(val){
    return val === val.toLowerCase() ? val.toUpperCase() : val.toLowerCase();
});

Solution 4:

Here is an alternative approach that uses bitwise XOR operator ^.
I feel this is more elegant than using toUppserCase/ toLowerCase methods

"So, today we have REALLY good day"
.split("")
.map((x) => /[A-z]/.test(x) ? String.fromCharCode(x.charCodeAt(0)  ^ 32) : x)
.join("")

Explanation
So we first split array and then use map function to perform mutations on each char, we then join the array back together.
Inside the map function a RegEx tests if the value is an alphabet character: /[A-z]/.test(x) if it is then we use XOR operator ^ to shift bits. This is what inverts the casing of character. charCodeAt convert char to UTF-16 code. XOR (^) operator flips the char. String.fromCharCode converts code back to char. If RegEx gives false (not an ABC char) then the ternary operator will return character as is.

References:

  • String.fromCharCode
  • charCodeAt
  • Bitwise operators
  • Ternary operator
  • Map function