Caesars Cipher - Looping Back

function rot13(str) { 
  for (i=0;i<=str.length-1;i++){
    console.log(String.fromCharCode(str.charCodeAt(i)));
    if (str.charCodeAt(i)>=65 || str.charCodeAt(i)<=90){
      str[i] = String.fromCharCode(str.charCodeAt(i)+13);
    }
  }
  return str;
}

When I run this code I get the message: TypeError: Cannot assign to read only property ‘0’ of string.
The console.logging prints all characters in order and also the first one, one more time in the end. I think this is the source of the error I get. How do I stop it from looping back?

You can’t mutate a string, strings are immutable. So when you try to do str[i] =, that’s gonna fail. Set up an empty string before the loop (var someVarName = ""), then you can set that string in every iteration with itself + the converted character (someVarName = someVarName + String.fromYaddaYadda). Then return that string once the loop ends.

1 Like

Thanks a lot!!! It helped a lot!

1 Like