Skip to content Skip to sidebar Skip to footer

Converting Odd And Even-indexed Characters In A String To Uppercase/lowercase In Javascript?

I need to make a function that reads a string input and converts the odd indexed characters in the string to upperCase and the even ones to lowerCase. function alternativeCase(str

Solution 1:

functionalternativeCase(string){
  returnstring.split('').map(function(c,i) {
    return i & 1 ? c.toUpperCase() : c.toLowerCase();
  }).join('');
}

Update 2019

These days it's pretty safe to use ES6 syntax:

constalternativeCase = string => string.split('')
  .map((c,i) => i & 1 ? c.toUpperCase() : c.toLowerCase()).join('');

Solution 2:

Try this:

functionalternativeCase(string){
    var output = "";
    for(var i = 0; i < string.length; i++){
        if (i % 2 != 0) {
            output += string[i].toUpperCase();
        }
        else {
            output += string[i].toLowerCase();
         }   
    }
    returnoutput;
}

Solution 3:

Strings in JavaScript are immutable, Try this instead:

functionalternativeCase(string){
     var newString = [];
     for(var i = 0; i < string.length; i++){
        if (i % 2 != 0) {
           newString[i] = string[i].toUpperCase();
        }
        else {
           newString[i] = string[i].toLowerCase();
        }   
     }
   return newString.join('');
}

Solution 4:

RegExp alternative that handles space between characters :

constalternativeCase = s => s.replace(/(\S\s*)(\S?)/g, (m, a, b) => a.toUpperCase() + b.toLowerCase());

console.log( alternativeCase('alternative Case') )

Post a Comment for "Converting Odd And Even-indexed Characters In A String To Uppercase/lowercase In Javascript?"