-2

Sorry for the noob question, I new in JS. Can't assign letter by index

var str="some string";
for( var i=0; i<str.length; i++) {
    var letter=str[i];    // it works
    letter.toUpperCase(); // it works too
    str[i]=letter; // try to assign new letter by index, but nothing happens..
}

Maybe is it because of implicit conversion from string to char..?

Amazing User
  • 3,473
  • 10
  • 36
  • 75
  • 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) – Charlie Jan 19 '16 at 10:49

1 Answers1

1

Strings are immutable in JS.

Unlike in languages like C, JavaScript strings are immutable. This means that once a string is created, it is not possible to modify it. However, it is still possible to create another string based on an operation on the original string.

You need to write your own function to assemble a new string out of the existing one.

String.prototype.replaceAt=function(index, character) {
    return this.substr(0, index) + character + this.substr(index+character.length);
}
Charlie
  • 22,886
  • 11
  • 59
  • 90