由于您的replace
不限于在字符串中的特定位置,它会在每次更换第一匹配的字符。 (它不会取代全部,因为它没有设置g
修饰符。)因此,首先将您的领先c
替换为d
,下一轮将o
替换为p
- 然后在第三轮中,当您的输入已经是dpd
,因此您获得epd
,因为第一个d
已被替换为e
。
这会更容易些,如果你没有使用replace
,而只是建立一个新字符串,你追加对当前输入的字符每次匹配的“下一个”字符,然后在结束时,您只需返回新的字符串。
编辑:
此外,您目前的实现不处理z
正确的,因为它与“下”字{
替换它,而应该宁可是一个a
。而Z
则变为[
,应改为A
。在Z
和a
之间,还有一些非字母字符,您可能不想替换。
这里是一个函数,实现了我上面的建议,并且也需要z
和Z
,以及非字母考虑:
function LetterChanges(str) {
var result = "";
for (var i = 0; i < str.length; i++) {
// handle "z"
if (122 == str.charCodeAt(i)) {
result += "a";
// handle "Z"
} else if (90 == str.charCodeAt(i)) {
result += "A";
// handle all other letter characters
} else if ((65 <= str.charCodeAt(i) && str.charCodeAt(i) <= 89) ||
(97 <= str.charCodeAt(i) && str.charCodeAt(i) <= 121)) {
result += String.fromCharCode(str.charCodeAt(i) + 1);
// append all other characters unchanged
} else {
result += str.charAt(i);
}
}
return result;
}
console.log(LetterChanges("AaZz+cod!foo")); // output: BbAa+dpe!gpp
http://jsfiddle.net/hvyft64p/3/
if ((65 <= str.charCodeAt(i) && str.charCodeAt(i) <= 89) ||
(97 <= str.charCodeAt(i) && str.charCodeAt(i) <= 121))
我用八十九分之六十五和97/121,和<=
这里进行比较,因为从逻辑的角度来看,这对我来说更有意义 - 这些是我们想要考虑的实际“边界”字母,A/Y和d a/y,所以使用这些数字直接使代码更具可读性。
非常感谢你的明确书面解释! – Jackie