lezeek
lezeek

Reputation: 49

How to alternate the case of a string

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()));
}

Upvotes: 3

Views: 14148

Answers (3)

Jorge Garcia
Jorge Garcia

Reputation: 51

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"))

Upvotes: 5

Mureinik
Mureinik

Reputation: 311853

You should iterate the string and alternate between upper-casing the character and lower-casing it:

for (var i=0; i<txt.length; i++) {
    var ch = String.fromCharCode(txt.charCodeAt(i);
    if (i % 2 == 1) {
        ch = ch.toUpperCase();
    } else {
        ch = ch.toLowerCase();
    }
    str =  str.concat(ch);
}

Upvotes: 1

pzp
pzp

Reputation: 6607

Here's a quick function to do it. It makes the entire string lowercase and then iterates through the string with a step of 2 to make every other character uppercase.

var alternateCase = function (s) {
  var chars = s.toLowerCase().split("");
  for (var i = 0; i < chars.length; i += 2) {
    chars[i] = chars[i].toUpperCase();
  }
  return chars.join("");
};

var txt = "hello world";
console.log(alternateCase(txt));

HeLlO WoRlD

The reason it converts the string to an array is to make the individual characters easier to manipulate (i.e. no need for String.prototype.concat()).

Upvotes: 5

Related Questions