I am having a problem in my code where the replace method is occasionally replacing the wrong letter. I think it has something to do with how the replace method works. Anyway, I read about the ASCII solution but I’m sticking to this till I get it working. Any thoughts?
function rot13(str) { // LBH QVQ VG!
let replaceLetter;
let strArr =[];
let splitStr = str.split(' ');
console.log(splitStr);
splitStr.forEach(el => {
console.log(el);
for(let i = 0; i < el.length; i++){
console.log(el[i]);
//Problem HERE
replaceLetter = replaceFunc(el[i]);
console.log(replaceLetter);
el = el.replace(el[i], replaceLetter);
console.log(el);
}
strArr.push(el);
});
console.log(splitStr);
console.log(strArr)
// Create a replace function
function replaceFunc(arg) {
let alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
let letter = arg
let newAlphaArr = alphabet.substring(0, alphabet.indexOf(arg));
let newStr = alphabet.concat(newAlphaArr);
let replace = newStr.charAt(newStr.indexOf(arg) + 13)
let newLetter = letter.replace(arg, replace);
return newLetter;
}
}
// Change the inputs below to test
rot13("SERR PBQR PNZC");