Converting Odd and Even-indexed characters in a st

2019-01-20 19:33发布

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(string){
    for(var i = 0; i < string.length; i++){
        if (i % 2 != 0) {
            string[i].toUpperCase();
        }
        else {
            string[i].toLowerCase();
        }   
    }
    return string;
}

How to fix my code?

4条回答
三岁会撩人
2楼-- · 2019-01-20 19:58

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

查看更多
家丑人穷心不美
3楼-- · 2019-01-20 19:58

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

查看更多
beautiful°
4楼-- · 2019-01-20 20:02

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;
}
查看更多
Melony?
5楼-- · 2019-01-20 20:15
function alternativeCase(string){
  return string.split('').map(function(c,i) {
    return i & 1 ? c.toUpperCase() : c.toLowerCase();
  }).join('');
}
查看更多
登录 后发表回答