a="12345"
a[2]=3
a[2]='9'
console.log(a) //=> "12345"
What is going on?? This quirk caused me 1 hour painful debugging. How to avoid this in a sensible way?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You cannot use brackets to rewrite individual characters of the string; only ‘getter’ (i.e. read) access is available. Quoting the doc (MDN):
That’s for “what’s going on” part of the question. And for “how to replace” part there’s a useful snippet (taken from an answer written long, long ago):
You may use as it is (biting the bullet of extending the JS native object) – or inject this code as a method in some utility object (obviously it should be rewritten a bit, taking the source string as its first param and working with it instead of
this).