Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()));
}
like image 745
lezeek Avatar asked Dec 05 '25 10:12

lezeek


2 Answers

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()).

like image 90
pzp Avatar answered Dec 07 '25 22:12

pzp


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"))
like image 42
Jorge Garcia Avatar answered Dec 08 '25 00:12

Jorge Garcia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!