Caesars Cipher - Where am I going wrong here?

Tell us what’s happening:

Hello!

I’ve completed the assignment already using a different solution - but I cannot see why my first attempt won’t work. I’ve spent quite a long time trying to spot the mistake - please can somebody put me out of my misery and tell me why it won’t work this way?

Your code so far


function rot13(str) {
	let regex = /[A-Z]/;

	for (let i = 0; i < str.length; i++) {
		if (regex.test(str[i])) {
			str[i].charCodeAt() < 78
				? (str = str.replace(str[i], String.fromCharCode(str[i].charCodeAt() + 13)))
				: (str = str.replace(str[i], String.fromCharCode(str[i].charCodeAt() - 13)));
		}
	}

	return str;
}

// Change the inputs below to test
console.log(rot13("SERR PBQR PNZC"));
console.log(rot13('LBH QVQ VG!'));

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.157 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/caesars-cipher

Thanks for your response Randell, that has really helped me to understand :slightly_smiling_face:

My understanding of how .replace() worked was wrong, now it is much clearer! Much appreciated :+1: