簡體   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