0

I just tried this code in Chrome deveoper tools:

var str = "1111111";
str[0] = 2;
2
console.log(str[0]);
1

As you can see, the output was 1, where I expected 2. My conclusion is this is not meant to be working like that, so I ask how would I get this to work - how would I change the first 'item' of the varable str to 2?

Danil Speransky
  • 29,891
  • 5
  • 68
  • 79
Nikola
  • 14,888
  • 21
  • 101
  • 165
  • 2
    JS Strings are immutable; http://stackoverflow.com/questions/51185/are-javascript-strings-immutable-do-i-need-a-string-builder-in-javascript , use an array or vanilla string operations `(str = "2" + str.substr ...)` – Alex K. Aug 29 '12 at 11:02
  • 1
    possible duplicate of [How do I replace a character at a particular index in Javascript?](http://stackoverflow.com/questions/1431094/how-do-i-replace-a-character-at-a-particular-index-in-javascript) – Shawn Chin Aug 29 '12 at 11:03
  • You can access string characters like an array, but not change them. – Bergi Aug 29 '12 at 11:08
  • Pretty sure index access fails in IE – Alex K. Aug 29 '12 at 11:10

4 Answers4

3

That is because in JavaScript strings are immutable objects. You should use substr function:

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

var str = '11111';
console.log(str.replaceAt(0, '2'));
Danil Speransky
  • 29,891
  • 5
  • 68
  • 79
0

From the rhino book:

In JavaScript, strings are immutable objects, which means that the characters within them may not be changed and that any operations on strings actually create new strings. Strings are assigned by reference, not by value. In general, when an object is assigned by reference, a change made to the object through one reference will be visible through all other references to the object. Because strings cannot be changed, however, you can have multiple references to a string object and not worry that the string value will change without your knowing it.

defuz
  • 26,721
  • 10
  • 38
  • 60
0

Try this out

str.replace(str.charAt(0), "2")
pkurek
  • 606
  • 4
  • 13
  • it's don't work, because `str.replace(str.charAt(1), "2")` return `"2111111"`, instead `"1211111"` – defuz Aug 29 '12 at 11:06
0

You need to split the string first.

So something like:

str = str.split('');

Then you can treat it as an array.

Mattyod
  • 1,349
  • 1
  • 9
  • 12