JavaScript Algorithms and Data Structures Projects: Caesars Cipher

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(' ');

  splitStr.forEach(el => {
    for(let i = 0; i < el.length; i++){
      //Problem HERE
      replaceLetter = replaceFunc(el[i]);
      el = el.replace(el[i], replaceLetter);



// Create a replace function
function replaceFunc(arg) {
  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");

So, your function replaceFunc() works. That’s the most important part.

The issue lies in your forEach(), which has a nested for loop inside of it, which uses replace() to modify the array splitStr in place.

That whole code block seems overly complex, when you can simply call replaceFunc() on each element in your splitStr array.

Right now, splitStr contains three elements, equivalent to the space-separated strings passed into your function rot13(). What if, instead of three elements, you made splitStr an array of each character, including spaces?

That way, using something like forEach(), you can loop through splitStr, and call replaceFunc() on each character, and push() each return value to strArr. You will need a conditional to deal with spaces, but that’s simple enough to do within a forEach().

Great idea. Thanks for your help. Over-complicating solutions is my big problem with the code I write :frowning: Thanks for the feedback.