在学习了5天的JavaScript之后,我写了一个只加密大写和小写字母的函数。
现在的问题是,我现在试图让它适用于短语(如果用户输入是"猫很棒",预期输出是" Jhaz hyl nylha&#34 ;),但我有问题让白色空间不受影响。
我尝试将/^[a-zA-Z]+$/
更改为/^[a-zA-Z\s]+$/
,但这不起作用。
function cipher() {
do {
word = prompt("write a word");
var output = "";
if (/^[a-zA-Z]+$/.test(word)) {
for (var i = 0; i < word.length; i++) {
var character = word.charCodeAt(i);
var caesarCiphLow = ((character - 65 + 33) % 26 + 65);
var caesarCiphUpp = ((character - 97 + 33) % 26 + 97);
if (character >= 65 && character <= 90) {
output = output + String.fromCharCode(caesarCiphLow);
} else if (97 <= character && character <= 122) {
output = output + String.fromCharCode(caesarCiphUpp);
}
}
return prompt("Your ciphered text is", output);
} else {
alert("You must enter a word, without spaces or numbers");
}
} while (word === "" || !/^[a-zA-Z]+$/.test(word));
}
答案 0 :(得分:0)
您缺少空格处理。 如果遇到空格,则需要将其放回输出字符串:
我对您的代码所做的唯一更改是:
添加您提到的\s
:
if (/^[a-zA-Z\s]+$/.test(word)) {
添加else语句
} else if (97 <= character && character <= 122) {
output = output + String.fromCharCode(caesarCiphUpp);
}
else
output = output + String.fromCharCode(character);
输入:猫很棒
输出:Jhaz hyl nylha