The String object in JavaScript and interactive demo
The String object
allows you to associate methods to strings.
There are differences between a variable that is an instance of String, and
a variable to which a string is assigned directly.
The constructor is also a mean to convert values to string objects.
The String converter may also be used to convert to string
The constructor accepts an argument that is a unique literal string or any
object that you want to convert to a string.
The syntax is:
var x = new String("string");
Example
var x = new String("demo");
A number may be converted to a string with the String object:
var s = String(10) + 5
document.write(s)
This displays 105 because the values are strings and so are concatenated, not addedd:
A variable can be
the argument of the constructor, as in any object:
var y = "demo";
var x = new String(y);
document.write(x);
The object is not interpreted by the eval function:
var x = new String("5 + 5");
var y = eval(x);
document.write(y);
This is not the case
of a single variable:
var x = "5 + 5";
document.write(x);
var y = eval(x);
document.write(y);
length attribute
Length
Number of characters
in the string.
Special HTML codes are
not interpreted:
var x = new String(" ");
document.write(x.length);
Trying string with
accents:
To length are also added attributes of Object.
Chars are accessed by an index
Like an array, we can indice a string to get the character at a given position:
var x = new String("demo");
document.write(x[2]) // should return m at 2 position from the beginning
The same result is obtained with the charAt method.
But is it also possible to replace a character at a position with its index?
x[1] = "Z";
document.write(x); // should display dZmo
Unfortunately this does not work! We must therefore use other methods of the String object:
x = x.substr(0,1) + "Z" + x.substr(2);
document.write(x);
Or more generally:
x = x.substr(0,index) + "Z" + x.substr(index+1);
chr and ord functions in JavaScript
The Unicode value of a character (provided by the ord function in other languages) is returned by this method:
x = y.charCodeAt(position);
The position is 0 when y has only one character.
To replace chr and get the character corresponding to a Unicode value, write: