JavaScript Algorithms and Data Structures Projects - Caesars Cipher

Tell us what’s happening:

Hi!
I don’t understand why i get: Uncaught Syntax Error. Syntax Error: Invalid regular expression: /?/: Nothing to repeat.

TESTS:

  • rot13("SERR PBQR PNZC") should decode to the string FREE CODE CAMP - my code works.
  • rot13("SERR CVMMN!") should decode to the string FREE PIZZA! - my code works.
  • rot13("GUR DHVPX OEBJA SBK WHZCF BIRE GUR YNML QBT.") should decode to the string THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG. - my code works.
  • rot13("SERR YBIR?") should decode to the string FREE LOVE? - my code doesn’t work.

I don’t use any regex in my code.

Your code so far

function rot13(str) {
    let alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    let arr = [];

    for (let i = 0; i < str.length; i++) {
        let x = alpha.search(str[i]);

        if ((str[i] == '!') ||
            (str[i] == ' ') ||
            (str[i] == '?') ||
            (str[i] == '.')) {
            arr.push(str[i]);
        } else {
            let y = alpha[x - 13];
            let z = x - 13;

            if (z < 0) {
                y = alpha[x + 13];
            }

            arr.push(y);
        }
    }

    return arr.join('');
}

rot13("SERR YBIR?");

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:107.0) Gecko/20100101 Firefox/107.0

Challenge: JavaScript Algorithms and Data Structures Projects - Caesars Cipher

Link to the challenge:

Because the search function will try to convert the value you give it to a regular expression, it is failing to do that with the question mark and results in the error (or that is my deduction anyway).

1 Like

dunno, mate.
wat does this do:?
let x = alpha.search(str[i]);
maybe check that out.

ah, method .search work as regular expression, I didn’t know it.
It’s easy to fix, thank you.

1 Like