Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript string assignment by index number quirk

Tags:

javascript

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?

like image 561
lkahtz Avatar asked Nov 14 '12 00:11

lkahtz


1 Answers

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

like image 198
raina77ow Avatar answered Nov 04 '22 17:11

raina77ow