I have been working on this code for FREECODECAMP but I've been stuck trying to get the answer to come out properly I can't get the code to come out with spaces in between the words. It is supposed to be Caesars cipher with a 13 digit shift in the letters. Can someone look at my code and tell me where I went wrong.
``
function rot13(str) {
let key = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let ans = '';
let keyAlph = key.substring(13) + key.substring(0,13);
for(let i =0; i < str.length; i++){
let temp = str.charAt(i);
let index = key.indexOf(temp);
if(temp !== NaN){
ans += keyAlph.[index];
}
}
return ans;
}
``
keyAlph.[index] should not contain that ".", and to add spaces between the words in the result, you can check if the current character is a space and add it to the answer string without applying the rot13 transformation, like this:
function rot13(str) {
let key = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let ans = '';
let keyAlph = key.substring(13) + key.substring(0,13);
for(let i = 0; i < str.length; i++) {
let temp = str.charAt(i);
let index = key.indexOf(temp);
if(temp !== ' ') { // check if character is not a space
ans += keyAlph[index];
} else {
ans += ' ';
}
}
return ans;
}