我正在进行CoderByte练习,我遇到了以下问题:
>使用JavaScript语言,让函数LetterChanges(str)获取传递的str参数,并使用以下算法对其进行修改。将字符串中的每个字母替换为字母表后面的字母(即c变为d,z变为a)。然后大写这个新字符串中的每个元音(a,e,i,o,u),最后返回这个修改后的字符串。
我在JSBin中写出来并且它运行良好(甚至te,但在CoderByte中它没有。我想问社区我写的是不正确的,这是CoderByte的一个问题,或者如果我的代码错误,问题出在JSBin上。
代码如下:
function LetterChanges(str) {
var iLetters = str.split('');
var newStr = [];
for (var i = 0; i < str.length; i++) {
if (/[a-y]/ig.test(iLetters[i])) {
newStr[i] = String.fromCharCode(iLetters[i].charCodeAt(0) + 1);
if (/[aeiou]/ig.test(newStr[i])) {
newStr[i] = newStr[i].toUpperCase();
}
} else if (/[z]/ig.test(iLetters[i])) {
newStr[i] = "A";
} else if (/[^A-Z]/ig.test(iLetters[i])) {
newStr[i] = iLetters[i];
}
}
return newStr.join('');
}
答案 0 :(得分:1)
看起来确实是他们后端JS跑者的一个错误。正如您所说,您的代码运行正常,应该被接受。值得向他们的支持imo报告。
以下是.replace()
到function LetterChanges(str) {
return str.replace(/[a-z]/ig, function(c) {
return c.toUpperCase() === 'Z' ? 'A' : String.fromCharCode(c.charCodeAt(0) + 1);
}).replace(/[aeiou]/g, function(c) {
return c.toUpperCase();
});
}
的替代解决方案:
{{1}}
答案 1 :(得分:0)
与以下替代
进行比较时,jsfiddle上的代码对我来说效果很好在CoderByte上,您的代码失败但以下工作正常。似乎是他们网站上的问题。
function letterChanges(str) {
var newString = "",
code,
length,
index;
for (index = 0, length = str.length; index < length; index += 1) {
code = str.charCodeAt(index);
switch (code) {
case 90:
code = 65;
break;
case 122:
code = 97
break;
default:
if ((code >= 65 && code < 90) || (code >= 97 && code < 122)) {
code += 1;
}
}
newString += String.fromCharCode(code);
}
return newString.replace(/[aeiou]/g, function (character) {
return character.toUpperCase();
});
}
console.log(LetterChanges("Then capitalize every vowel in this new string (a, e, i, o, u) and finally return this modified string."));
console.log(letterChanges("Then capitalize every vowel in this new string (a, e, i, o, u) and finally return this modified string."));
输出
UIfO dbqjUbmjAf fwfsz wpxfm jO UIjt Ofx tUsjOh (b, f, j, p, v) bOE gjObmmz sfUvsO UIjt npEjgjfE tUsjOh. fiddle.jshell.net/:70
UIfO dbqjUbmjAf fwfsz wpxfm jO UIjt Ofx tUsjOh (b, f, j, p, v) bOE gjObmmz sfUvsO UIjt npEjgjfE tUsjOh.
答案 2 :(得分:0)
来自@FabrícioMatté答案的另一个解决方案
并且有一点解释是使用正则表达式使用/[a-z]/
从a到z获取第一个字母表,并使用String.fromCharCode(Estr.charCodeAt(0)+1)
通过向每个字符串的ASCII添加一个来替换它们,其余的是使用再次使用regex找到元音的问题[aeiou]
并返回大写字符串。
function LetterChanges(str) {
return str.replace(/[a-z]/ig, function(Estr) {
return String.fromCharCode(Estr.charCodeAt(0)+1);
}).replace(/[aeiou]/ig, function(readyStr) {
return readyStr.toUpperCase();
})
}