Letter → next letter and capitalize vowels

孤街醉人 提交于 2019-12-13 08:49:43

问题


This code still doesn't seem to be working. It has no errors anymore, but it only returns blank brackets like this {}. It is supposed to turn each letter in str into the next letter and capitalize each vowel. Any ideas?

function LetterChanges(str) { 
str = str.split("");//split() string into array
  for(var i=0;i<str.length;i++){//for loop that checks each letter
    if(str[i].match(/[a-y]/i)){
      str[i]=String.fromCharCode(str[i].charCodeAt(0)+1);
        }else if(str[i].match("z")){
          str[i] = "a";
        }
    if(str[i].match(/[aeiou]/i)){
       str[i] = str[i].toUpperCase();
       }

  }
   str = str.join("");
  //modifies letter by adding up in alphabet
  //capitalizes each vowel
  //join() string


  return str; 
}

回答1:


It looks like this method can by simplified to just a few calls to .replace:

function LetterChanges(str) { 
    return str
        .replace(/[a-y]|(z)/gi, function(c, z) { return z ? 'a' : String.fromCharCode(c.charCodeAt(0)+1); })
        .replace(/[aeiou]/g, function(c) { return x.toUpperCase(); });
}

LetterChanges("abcdefgxyz"); 
//            "bcdEfghyzA"

Or alternatively, a single call to .replace, like this:

function LetterChanges(str) { 
    return str.replace(/(z)|([dhnt])|[a-y]/gi, function(c, z, v) {
        c = z ? 'A' : String.fromCharCode(c.charCodeAt(0)+1); 
        return v ? c.toUpperCase() : c; 
    })
}

LetterChanges("abcdefgxyz"); 
//            "bcdEfghyzA"


来源:https://stackoverflow.com/questions/21296270/letter-%e2%86%92-next-letter-and-capitalize-vowels

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