Caesars Cipher: How to add back spaces

Tell us what’s happening:
I managed to decode the string but in the process I deleted the spaces, how do I go about modifying only the characters [a-zA-Z]?

Your code so far


function rot13(str){
  let arr = [...str]
  const letters = ['A', 'B', 'C', 'D', 'E', 'F',
  'G', 'H', 'I', 'J', 'K', 'L',
  'M', 'N', 'O', 'P', 'Q', 'R',
  'S', 'T', 'U', 'V', 'W', 'X',
  'Y', 'Z']
  let regex = /[a-zA-Z]/
  for (let l of str){
    if (regex.test(l)){
      arr.splice(str.indexOf(l), 1, letters[letters.indexOf(l) - 13])
      if (letters[letters.indexOf(l) - 13] == undefined){
        arr.splice(arr.indexOf(undefined), 1, letters[letters.indexOf(l) + 13])
      }
    }
  }
  console.log(arr)
  //return arr.join("")
}

console.log(rot13("SERR PBQR PNZC"));

I also have this code:

function rot13(str){
  let arr = [...str]
  const letters = ['A', 'B', 'C', 'D', 'E', 'F',
  'G', 'H', 'I', 'J', 'K', 'L',
  'M', 'N', 'O', 'P', 'Q', 'R',
  'S', 'T', 'U', 'V', 'W', 'X',
  'Y', 'Z']
  for (let l of str){
    if (letters.includes(l)){
      arr.splice(str.indexOf(l), 1, letters[letters.indexOf(l) - 13])
      if (letters[letters.indexOf(l) - 13] == undefined){
        arr.splice(arr.indexOf(undefined), 1, letters[letters.indexOf(l) + 13])
      }
    }
  }
  return arr.join("")
}

console.log(rot13("SERR PBQR PNZC"));


Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:84.0) Gecko/20100101 Firefox/84.0.

Challenge: Caesars Cipher

Link to the challenge:

the spaces are not the issue.

what does that console.log prints?

the array? I don’t get it

I copied str into arr, what I’m doing is replacing the contents of arr (which is the string) with .splice using -13 or +13 if the value returns undefined. In the second example I posted I managed to decode the string but wasn’t able to decode in a way which I can maintain the spaces so I just ditched that code

and does the array have the value you expect?

I don’t know to what you refer as values, but I will convert to a string with .join so I assume it doesn’t matter that its an array, if you refer to the values it contain, then no since there are some letters which don’t go there and that is what I’m trying to understand, the output is:

[
  'F', 'R', 'E', 'R',
  ' ', 'C', 'O', 'D',
  'R', ' ', 'P', 'A',
  'M', 'P'
]

you use indexOf, and then use the index returned from that, meaning you affect only the first instance of that letter, not the others