2017-10-15 366 views
0

經過5天的JavaScript學習後,我寫了一個函數,只能讀取大寫和小寫字母。JavaScript密碼功能允許空格

問題是,現在我試圖讓它也適用於短語(如果用戶輸入是「貓是偉大的」,預期的輸出是「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)); 

} 
+0

只是單挑:你不需要'do-while'循環,你可以使用一般的while循環,它可以工作(可能)。 –

回答

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