Converting Odd and Even-indexed characters in a string to uppercase/lowercase in Javascript?

ⅰ亾dé卋堺 提交于 2019-12-02 11:12:37

Try this:

function alternativeCase(string){
    var output = "";
    for(var i = 0; i < string.length; i++){
        if (i % 2 != 0) {
            output += string[i].toUpperCase();
        }
        else {
            output += string[i].toLowerCase();
         }   
    }
    return output;
}
function alternativeCase(string){
  return string.split('').map(function(c,i) {
    return i & 1 ? c.toUpperCase() : c.toLowerCase();
  }).join('');
}

Strings in JavaScript are immutable, Try this instead:

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

RegExp alternative that handles space between characters :

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

console.log( alternativeCase('alternative Case') )
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!