Swap Case on javascript

guys! Get a little simplier code:

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

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)

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"

Tags:

Javascript