Tell us what’s happening:
I’m creating a function that decodes a caesars cipher that shifts all letters by 13 places. With the code that I have so far, it produces an error saying that it “cannot assign to read only property of ‘0’ of string”. What am I doing wrong here?
Your code so far
function rot13(str)
{ // LBH QVQ VG!
str.split("");
for(var i = 0; i < str.length; i++)
{
if(str[i] !== " ")
{
str[i] = String.fromCharCode(str[i].charCodeAt(i) + 13);
}
}
str.join("");
return str;
}
// Change the inputs below to test
rot13("SERR PBQR PNZC");
Your browser information:
Your Browser User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36
.
Link to the challenge:
str.split("");
will not change the string str but instead return a new list. Since this newly created list is not stored in a variable, it is lost. I changed your code a bit by adding a variable assignment on line 4 and by returning the value from str.join("");
directly at the end of the function.
function rot13(str)
{ // LBH QVQ VG!
str = str.split("");
for(var i = 0; i < str.length; i++)
{
if(str[i] !== " ")
{
str[i] = String.fromCharCode(str[i].charCodeAt(i) + 13);
}
}
return str.join("");
}
// Change the inputs below to test
rot13("SERR PBQR PNZC");
I have no idea what’s wrong with this code. Should it not print all the letters? It only prints the first one and it prints it as A rather than F, which is wrong based on my algorithm. Also, how do you debug your own code? I’ve tried using document.write(); and console.log(); but, at least in this editor, nothing appears. Anyway, here’s my latest code:
function rot13(str)
{ // LBH QVQ VG!
str = str.toUpperCase();
str = str.split("");
for(var i = 0; i < str.length; i++)
{
if(str[i] !== " ")
{
str[i] = String.fromCharCode(str[i].charCodeAt(i) - 13);
if((str[i].charCodeAt(i) - 13) <= 65)
{
str[i] = "A";
}
}
}
return str.join("");
}
// Change the inputs below to test
rot13("SERR PBQR PNZC");