JavaScript 密码函数允许空格
JavaScript cipher function allow spaces
学习JavaScript 5天后,我写了一个只加密大小写字母的函数。
问题是现在我正在尝试让它也适用于短语(如果用户输入是 "Cats are great",预期输出是 "Jhaz hyl nylha"),但我遇到了问题让空白保持不变。
我尝试将 /^[a-zA-Z]+$/
更改为 /^[a-zA-Z\s]+$/
,但没有用。
PS: 是的,这是一个家庭作业,但我已经得到了它的成绩,因为我才刚刚开始学习我仍在努力使我的功能更好并学到更多,任何帮助将不胜感激。
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));
}
您缺少对 space 的处理。
如果遇到space,需要把它放回输出字符串:
我对上面的代码所做的唯一更改是:
添加您提到的\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
学习JavaScript 5天后,我写了一个只加密大小写字母的函数。
问题是现在我正在尝试让它也适用于短语(如果用户输入是 "Cats are great",预期输出是 "Jhaz hyl nylha"),但我遇到了问题让空白保持不变。
我尝试将 /^[a-zA-Z]+$/
更改为 /^[a-zA-Z\s]+$/
,但没有用。
PS: 是的,这是一个家庭作业,但我已经得到了它的成绩,因为我才刚刚开始学习我仍在努力使我的功能更好并学到更多,任何帮助将不胜感激。
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));
}
您缺少对 space 的处理。 如果遇到space,需要把它放回输出字符串:
我对上面的代码所做的唯一更改是:
添加您提到的\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