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

后端 未结 4 728
眼角桃花
眼角桃花 2021-01-26 11:12

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          


        
相关标签:
4条回答
  • 2021-01-26 11:19

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

    0 讨论(0)
  • 2021-01-26 11:21

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

    0 讨论(0)
  • 2021-01-26 11:36
    function alternativeCase(string){
      return string.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:

    const alternativeCase = string => string.split('')
      .map((c,i) => i & 1 ? c.toUpperCase() : c.toLowerCase()).join('');
    
    0 讨论(0)
  • 2021-01-26 11:39

    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;
    }
    
    0 讨论(0)
提交回复
热议问题