7
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?

lkahtz
  • 4,706
  • 8
  • 46
  • 72
  • 1
    same here it took half an hour.... – Gaurav Bhardwaj Apr 04 '20 at 05:29
  • How could `a[2]=3` clarify, whether the behaviour is like expected or not? The outcome seems to be the same in both cases. Does it matter that `3` is not a string literal, but `'9'` is? – Leif Jul 20 '23 at 14:51

3 Answers3

8

You cannot use brackets to rewrite individual characters of the string; only 'getter' (i.e. read) access is available. Quoting the doc (MDN):

For character access using bracket notation, attempting to delete or assign a value to these properties will not succeed. The properties involved are neither writable nor configurable.

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):

String.prototype.replaceAt = function(index, char) {
    return this.slice(0, index) + char + this.slice(index+char.length);
}

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).

Community
  • 1
  • 1
raina77ow
  • 103,633
  • 15
  • 192
  • 229
4

According to this question, this is not supported among all browsers.

If your strings aren't too long, you can do this relatively easy like that:

var a="12345";
a = a.split("");
a[2]='9';
a = a.join("");
console.log(a);
Community
  • 1
  • 1
David Müller
  • 5,291
  • 2
  • 29
  • 33
1
var letters = a.split('');
letters[2] = 3;
letters[2] = 9;
console.log(letters.join(''));

http://jsfiddle.net/XWwKz/

Cheers

Madbreaks
  • 19,094
  • 7
  • 58
  • 72