Tell us what’s happening:
Trying to create an if statement within a for loop and another for loop within else statement. The code works for one letter strings, but fails to loop back through remaining string.
How can I get for loop to continue to iterate through str after completing if statment?
I realize there is probably a much easier way and more convention way to achieve the same results, but I am trying to write the code all by myself without looking at the hints provided and this is what I thought of. I can write it with while loop inside a for loop as well.
Your code so far
function rot13(str) { // LBH QVQ VG!
let preLetters = ['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'];
let rot13Letters = ['N', 'O', 'P', 'Q', 'S', 'T', 'U', 'V', 'W', 'X', 'Y','Z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M'];
let caesarCipher = '';
for (let i=0; i <= str.length; i++){
if (str[i] === /\W/gi){
return caesarCipher += str[i];
}
else {
for (let j=0; j<preLetters.length; j++){
while (str[i] === preLetters[j]){
return caesarCipher += rot13Letters[j];
}}}}
return caesarCipher;
}
// Change the inputs below to test
console.log(rot13("ABC"));
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36
.
Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/caesars-cipher/