【问题标题】:Letter → next letter and capitalize vowels字母 → 下一个字母和大写元音
【发布时间】:2014-02-13 07:09:45
【问题描述】:

此代码似乎仍然无法正常工作。它不再有错误,但它只返回像{} 这样的空白括号。它应该将str 中的每个字母变成下一个字母并将每个元音大写。有什么想法吗?

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; 
}

【问题讨论】:

标签: javascript regex string for-loop capitalize


【解决方案1】:

看起来这个方法可以简化为只调用几次.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"

或者,单独调用.replace,如下所示:

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"

【讨论】:

    猜你喜欢
    • 2018-07-08
    • 1970-01-01
    • 2015-10-24
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-01
    相关资源
    最近更新 更多