Caesar cipher help

Hello. This is my first time creating a post. I am currently working on the caesar cipher problem from freecodecamp javascript section. I am having hard time figuring out what the error is in my code or how to explain it. I know where its messing up, However I do not know why. I will post the code. I can see that any letter before O does not switch however any letter after it does switch to the correct letter. Thank you very much.

function rot13(str) {
  const letters = {    // cipher translation         
    A: 'N',
    B: 'O',
    C: 'P',
    D: 'Q',
    E: 'R',
    F: 'S',
    G: 'T',
    H: 'U',
    I: 'V',
    J: 'W',
    K: 'X',
    L: 'Y',
    M: 'Z',
    N: 'A',
    O: 'B',
    P: 'C',
    Q: 'D',
    R: 'E',
    S: 'F',
    T: 'G',
    U: 'H',
    V: 'I',
    W: 'J',
    X: 'K',
    Y: 'L',
    Z: 'M'
// looping through keys searching for the key within the string. then replacing with the value of that letters[key]

for(let key in letters) {   
  let regex = new RegExp(key, 'g');
  str = str.replace(regex, letters[key]);
  return str;

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

1 Like

Ah, I see what I think is happening.

Suppose your word is "ABA"

First you replace the As, so it becomes "NBN".

Then you replace the B, so it becomes "NON".

You should be done at this point, but…

Your loop keeps going and eventually replaces the Ns, so it becomes "AOA" and then replaces the O' so it becomes “ABA”`.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.