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?

4
  • 2
    JS Strings are immutable; stackoverflow.com/questions/51185/… , use an array or vanilla string operations (str = "2" + str.substr ...) Commented Aug 29, 2012 at 11:02
  • 1
    possible duplicate of How do I replace a character at a particular index in Javascript? Commented Aug 29, 2012 at 11:03
  • You can access string characters like an array, but not change them. Commented Aug 29, 2012 at 11:08
  • Pretty sure index access fails in IE Commented Aug 29, 2012 at 11:10

4 Answers 4

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'));
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

0

Try this out

str.replace(str.charAt(0), "2")

1 Comment

it's don't work, because str.replace(str.charAt(1), "2") return "2111111", instead "1211111"
0

You need to split the string first.

So something like:

str = str.split('');

Then you can treat it as an array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.