Trying interactively methods of the String object in JavaScript
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 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);
The string object has a 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.