The String type is the object representation for strings and is created using the String constructor as follows:
var stringObject = new String("hello world");
The methods of a String object are available on all string primitives.
valueOf(), toLocaleString(), and toString() from String type return the object's primitive string value.
var stringValue = "hello world";
console.log(stringValue.toString());
console.log(stringValue.valueOf());
console.log(stringValue.toLocaleString());
The code above generates the following result.
Each instance of String contains a property, length
, which indicates the number of
characters in the string. Consider the following example:
var stringValue = "hello world";
console.log(stringValue.length); //"11"
The code above generates the following result.
Two String methods access specific characters: charAt()
and charCodeAt()
.
They both accept zero-based position as the parameter.
The charAt()
method returns the character in the given position as a single-character string.
var stringValue = "hello world";
console.log(stringValue.charAt(1)); //"e"
The code above generates the following result.
charCodeAt() returns the character code instead of the actual character.
var stringValue = "hello world";
console.log(stringValue.charCodeAt(1)); //outputs "101"
This example outputs "101", which is the character code for the lowercase "e" character.
The code above generates the following result.
You can also use bracket notation with a numeric index to access a specific character in the string.
var stringValue = "hello world";
console.log(stringValue[1]); //"e"
The code above generates the following result.