Caesars cipher project issue

Tell us what’s happening:
I guess there is some issue with replace part. Can someone explain me what is the issue with this code?

  **Your code so far**

function rot13(str) {
let regex=/[A-Z]/g;
for(let i in str){
   let replaceWith=str[i].match(regex)?String.fromCharCode(
    str.charCodeAt(i)-78 < 0 ? str.charCodeAt(i)+13 :str.charCodeAt(i)-13
    ):str[i];
  console.log(str[i],replaceWith)  
  str=str.replace(str[i], replaceWith);
}
return str;
}



console.log(rot13("SERR PBQR PNZC"));

Challenge: Caesars Cipher

Link to the challenge:

function rot13(str) {
  let arr=str.split("");
  let regex=/[A-Z]/;
  for(let i in str){
     let replaceWith=str[i].match(regex)?String.fromCharCode(
      str.charCodeAt(i)-78 < 0 ? str.charCodeAt(i)+13 :str.charCodeAt(i)-13
      ):str[i];
    console.log(str[i],replaceWith)
    arr[i]=replaceWith;  
  }
  return arr.join("");
}



console.log(rot13("SERR PBQR PNZC"));

If I change my code to like above it works fine.

You can post solutions that invite discussion (like asking how the solution works, or asking about certain parts of the solution). But please don’t just post your solution for the sake of sharing it.
If you post a full passing solution to a challenge and have questions about it, please surround it with [spoiler] and [/spoiler] tags on the line above and below your solution code.

1 Like

first iteriation str[i] is S
it becomes

FERR PBQR PNZC

second iteration str[i] is E

FRRR PBQR PNZC

third iteration, str[i] is R

FERR PBQR PNZC

fourth iteration, str[i] is R

FEER PBQR PNZC

ecc

does this answer your question of what’s going wrong?


The replace() method returns a new string with some or all matches of a pattern replaced by a replacement . […] If pattern is a string, only the first occurrence will be replaced.

sorry, that was wrong, I just edited the post, but yeah, replace isn’t the best thing here

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