Search code examples
javascriptstringcaesar-cipher

Why Is My Caesar Cipher Code Skipping Over Some Characters?


I have the code below for a Caesar Cipher to increment by 13 characters on each input character. It works for almost all inputs, but will seemingly skip over random chacaters. I just can't seem to figure out why?! I'm still learning, so any help would be fantastic!

The input is a coded string of characters that will be output with each character shifted forward 13 places. The expected output should be a readable string.

If I input rot13('GUR DHVPX OEBJA SBK WHZCF BIRE GUR YNML QBT.') I would expect 'THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG.' But instead I get 'T H E Q U I C K B R O W N F B X J H M P S B V R E G U R L A Z Y D B G .'

I appreciate this could be a duplicate, but I couldn't find an answer to this particular problem so far.

function rot13(str) {
  
  let newStr = [];

  for (let i = 0; i < str.length; i++) {
    let charNum = str.charCodeAt(i);
    console.log(charNum);
    if (charNum > 64 && charNum < 78) {
      let res = str.replace(str[i], String.fromCharCode(charNum + 13));
      newStr.push(res[i]);
    } else if (charNum > 77 && charNum < 91) {
      let res = str.replace(str[i], String.fromCharCode(charNum - 13));
      newStr.push(res[i]);
    } else {
      newStr.push(str[i]);
    }
  }

  console.log(newStr);
  return newStr.join(" ");
}

rot13('GUR DHVPX OEBJA SBK WHZCF BIRE GUR YNML QBT.');


Solution

  • String.fromCharCode(charNum + 13) & String.fromCharCode(charNum - 13) are all you need. You don't need to replace the char at index i in str.

    newStr.push(String.fromCharCode(charNum + 13));
    newStr.push(String.fromCharCode(charNum - 13));