Hi, spacing in my decoded ROT13 cipher keeps returning "undefined", trying to figure out how to remove all whitespace

Here’s my code;
function rot13(str) {

const input = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';

const output = 'NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm';

let encoded = '';

for (let i=0; i < str.length; i++) {

    const index = input.indexOf(str[i]);

    encoded += output[index];

}

return encoded;

}

console.log(rot13(“SERR PBQR PNZC”));

The issue with your code is that you are assuming every character in str can be found in output. You only want to encode letters, so what do you want to do when a character in str is not a letter? You need to take this into account in the for loop.

Here’s what I did on the for loop, Thanks for pointing it out. It works now.

for(let i=0; i < str.length; i++){

if(str.charCodeAt(i)>=65 && str.charCodeAt(i)<=77){

  arr.push(String.fromCharCode(str.charCodeAt(i)+13));

} else if(str.charCodeAt(i)>=78 && str.charCodeAt(i)<=90){

  arr.push(String.fromCharCode(str.charCodeAt(i)-13));

} else if(str.charCodeAt(i)<65){

arr.push(str[i]);

}

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