faqts : Computers : Programming : Languages : JavaScript : Language Core : Strings

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

7 of 10 people (70%) answered Yes
Recently 5 of 8 people (63%) answered Yes

Entry

Why can't I change a string?

Feb 21st, 2000 08:24
Martin Honnen,


Strings are immutable objects, so while you can use one string to build 
a new one you can't change the chararcters of a string.
For example NN allows to treat strings like arrays to read characters 
in a string by indexing them e.g.
  var string = 'Kibo';
  var char = string[0];  // this doesn't work with IE
but it is not possible to set a character e.g.
  string[1] = 'X';
is ignored and doesn't change the string.
You need to build a new string using string functions like 
substring/replace/indexOf e.g.
  var string1 = 'Kibo';
  var string2 = 'X' + string1.substring(1);
or 
  var string1 = 'Kibo';
  var string2 = string1.replace(/K/g, "X");
Of course if you don't want to keep the old string around you can 
reassign to the same variable
  var string1 = 'Kibo';
  string1 = string1.replace(/K/g, "X");
but you are building a new string.
That is particularly important when building your own string methods. 
These can never change the called string object but only construct and 
return a new one. So
  function stringReverse () {
    var r = '';
    for (var i = this.length - 1; i >= 0; i--)
      r += this.charAt(i);
    return r;
  }
  String.prototype.reverse = stringReverse;
is unable to change the string it is called on e.g.
  var string = 'Kibo';
  string.reverse();
doesn't change the string but you need to reassign
  string = string.reverse();