问题
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