简体   繁体   English

JavaScript密码功能允许空格

[英]JavaScript cipher function allow spaces

After been learning JavaScript for 5 days, I've wrote a function that ciphers only upper and lower case letters. 学习了5天的JavaScript之后,我编写了一个仅对大小写字母进行加密的函数。

The problem is that now I'm trying to make it work for phrases too (if user input is "Cats are great", the expected output is "Jhaz hyl nylha"), but I'm having problems to let white spaces untouched. 问题是现在我也尝试使它也适用于短语(如果用户输入为“ Cats great”,预期输出为“ Jhaz hyl nylha”),但是我遇到了让空白不受影响的问题。

I tried changing /^[a-zA-Z]+$/ to /^[a-zA-Z\\s]+$/ but that didn't work. 我尝试将/^[a-zA-Z]+$/更改为/^[a-zA-Z\\s]+$/但这没有用。

PS: Yes, this was a homework but I already got a grade for it, as I'm just starting learning I'm still working on it to make my function better and learn more, any help will be appreciated. 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));

}

You are missing the handling of spaces. 您缺少对空格的处理。 If you encounter a space, you need to put it back to the output string: 如果遇到空格,则需要将其放回输出字符串:

The only changes I made to your code above is: 我对您的代码所做的唯一更改是:

Adding the \\s you have mentioned: 添加您提到的\\s

if (/^[a-zA-Z\s]+$/.test(word)) {

Adding else statement 添加else语句

} else if (97 <= character && character <= 122) {
    output = output + String.fromCharCode(caesarCiphUpp);
}
 else
    output = output + String.fromCharCode(character);

Input: Cats are great 输入:猫很棒

Output: Jhaz hyl nylha 输出:Jhaz hyl nylha

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM