How to alternate the case of a string

Viewed 9252

I'm working on alternating the case of a string (for example asdfghjkl to AsDfGhJkL). I tried to do this. I found some code that is supposed to do it, but it doesn't seem to be working.

var str="";

var txt=document.getElementById('input').value;

for (var i=0; i<txt.length; i+2){
    str = str.concat(String.fromCharCode(txt.charCodeAt(i).toUpperCase()));
}
3 Answers

Here an ES6 approach:

function swapCase(text) {
    return text.split('').map((c,i) => 
        i % 2 == 0 ? c.toLowerCase() : c.toUpperCase()
    ).join('');   
}

console.log(swapCase("test"))
Related