繁体   English   中英

JavaScript密码功能允许空格

[英]JavaScript cipher function allow spaces

学习了5天的JavaScript之后,我编写了一个仅对大小写字母进行加密的函数。

问题是现在我也尝试使它也适用于短语(如果用户输入为“ Cats 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));

}

您缺少对空格的处理。 如果遇到空格,则需要将其放回输出字符串:

我对您的代码所做的唯一更改是:

添加您提到的\\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

暂无
暂无

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

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