Help needed in Caesar Cipher!

Tell us what’s happening:

Okay, so my letters are converting to their proper required values, but I don’t know why my non-word chars are also converting. I know there’s something wrong with my regex (or the if statement) on line 10 of my code. But can’t figure out what it is.

Your code so far


function rot13(str) {

let strArr = str.split("");
let changedLetter;
let resultArr = [];

for(let i = 0; i < strArr.length; i++) {
  let count = 1;
  changedLetter = strArr[i];
  if(strArr[i] !== /[^A-Z]/) {
    for(let j = 1; j < 14; j++) {
      if(strArr[i].charCodeAt() + j != 91) {
        changedLetter = String.fromCharCode(strArr[i].charCodeAt() + count);
        count++;
      } else {
        strArr[i] = String.fromCharCode(65);
        changedLetter = strArr[i];
        count = 1;
      }
    }
  } else {
    changedLetter = str[i];
  }
  resultArr.push(changedLetter);
}
console.log(resultArr.join(""));
return resultArr.join("");
}

rot13("SERR PBQR PNZC"); // FREE-CODE-CAMP
rot13("SERR CVMMN!"); // FREE-PIZZA.
rot13("SERR YBIR?"); // FREE-LOVEL
rot13("GUR DHVPX OEBJA SBK WHZCF BIRE GUR YNML QBT."); // THE-QUICK-BROWN-FOX-JUMPS-OVER-THE-LAZY-DOG;

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36.

Challenge: Caesars Cipher

Link to the challenge:

That is saying “if the current character is not literally /[^A-Z]/”, you aren’t doing any kind of regex test. It’s a regex literal, which (if that condition doesn’t error) will be an object, so you are testing if the current character is not an object. Which is never is. You have to use methods here (either String methods that allow regex parameters, or RegExp methods) that allow JS to evaluate the regex. For the code you have, the one you probably want:

Thank you! Got it! :slight_smile:

1 Like