Tell us what’s happening:
Hello Dear Camper,
i already saw other solutions with CharToCode and i think i can do it with that approach. I would still like to know why the code below is behaving weird. For the example below i get from “SERR PBQR PNZC” the result “FEEE PODR CAMC”.
The third iteration might be interesting. It should change the str[2] to E, but it actually replaces str[1] with the desired character…
Thanks in advance for your help!
Your code so far
function rot13(str) { // LBH QVQ VG!
//Initialize Alphabet + 13 more characters for the shift
let alphabet = ["A","B","C","D","E","F","G","H", "I", "J", "K", "L", "M", "N", "O", "P","Q","R","S","T","U","V","W","X","Y","Z", "A","B","C","D","E","F","G","H", "I", "J", "K", "L", "M"];
let regEx = /^[A-Z]+$/i;
console.log(str);
//ForLoop for every Character in str
for(let i = 0; i < str.length; i++){
//RegEx if Character is in Alphabet
if(regEx.test(str[i])){
//Find Character Index in Alphabet
for(let x = 0; x < 26;x++){
if(str[i]==alphabet[x]){
//Replace Character with value of alphabet[index+13]
str = str.replace(str[i], alphabet[x+13]);
console.log(str);
break;
}
}
}
}
console.log(str);
return str;
}
// Change the inputs below to test
rot13("SERR PBQR PNZC");
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:61.0) Gecko/20100101 Firefox/61.0
.
Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/caesars-cipher