Search code examples
javascriptwhitespacecaesar-cipherphrases

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.

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.

I tried changing /^[a-zA-Z]+$/ to /^[a-zA-Z\s]+$/ but that didn't work.

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.

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));

}

Solution

  • 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:

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

    Adding else statement

    } 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