JavaScript Algorithms and Data Structures Projects - Caesars Cipher

Hello,
Could someone tell me why my code works for half letters only?
function rot13(str) {
let alphabet = “ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ”;

let regex= /\w/;
for (let i=0; i<str.length; i++){
if(regex.test(str[i])){
let myIndex= (alphabet.indexOf(str[i]))+13

str = str.replace(str[i] , alphabet[myIndex]);

}

}

return str;
}

here are some examples:
console.log(rot13(“SERR CVMMN!”))

console.log(rot13(“SERR PBQR PNZC”))
FEER PIZZA!
FEEE PODR CAMC

Your code so far

function rot13(str) {
  let alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ";
  
let regex= /\w/;
for (let i=0; i<str.length; i++){
  if(regex.test(str[i])){
 let myIndex= (alphabet.indexOf(str[i]))+13
         
    str = str.replace(str[i] , alphabet[myIndex]);
  }

}

  return str;
  }



console.log( /\w/g.test("!"))
console.log(rot13("SERR CVMMN!"))
console.log(rot13("SERR PBQR PNZC"))
console.log("SERR PBQR PNZC".match(/\w/))

Your browser information:

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

Challenge: JavaScript Algorithms and Data Structures Projects - Caesars Cipher

Link to the challenge:

What happens if you replace A with N and then N with A ?

You mean this is my code is doing?
You know, if you look at some tests, for example the one that returns free code camp, you will see that some letters have been changed but some remained the same.

There trying to help you see a pattern of what might be going on with your code. If you use “NA” you get “NA” back, and “AN” gives you “AN” back. Both of which are odd things for your code to be doing if A ↔ N. If you haven’t toss some more console.logs in your code to see where things might not be working how you expect them to be, maybe with a string like “NANANANA”.

1 Like

Thanks. I will check more test cases to figure it out.

If myIndex equals str[i] + 13, what about letters in the second half of the alphabet [index > 13]? If you add 13 to those, the value would be greater than alphabet.length. You would have to add for letters A through M, but subtract for letters N through Z.

EDIT: Oh wait nvm I see that you went A - Z twice.

So did you figure it out?

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