The String object is used for storing and manipulating text.
A string simply stores a series of characters like "John Doe".
A string can be any text inside quotes. You can use simple or double quotes:
You can access each character in a string with its position (index):
String indexes are zero-based, which means the first character is [0], the second is [1], and so on.
You can use quotes inside a string, as long as they don't match the quotes surrounding the string:
Or you can put quotes inside a string by using the \ escape character:
The length of a string (a string object) is found in the built in property length:
The indexOf() method returns the position (as a number) of the first found occurrence of a specified text inside a string:
The method returns -1 if the specified text is not found.
The lastIndexOf() method starts searching at the end of the string instead of at the beginning.
The match() method can be used to search for a matching content in a string:
The replace() method replaces a specified value with another value in a string.
A string is converted to upper/lower case with the methods toUpperCase() / toLowerCase():
A string is converted to an array with the built in method string.split():
The backslash (\) can be used to insert apostrophes, new lines, quotes, and other special characters into a string.
Look at the following JavaScript code:
In JavaScript, a string is started and stopped with either single or double quotes. This means that the string above will be chopped to: We are the so-called
To solve this problem, you must place a backslash (\) before each double quote in "Viking". This turns each double quote into a string literal:
JavaScript will now output the proper text string: We are the so-called "Vikings" from the north.
The table below lists other special characters that can be added to a text string with the backslash sign:
| Code | Outputs |
|---|---|
| \' | single quote |
| \" | double quote |
| \\ | backslash |
| \n | new line |
| \r | carriage return |
| \t | tab |
| \b | backspace |
| \f | form feed |
Properties:
Methods:
For a complete reference of all the properties and methods that can be used with the String object, go to our Complete String Object Reference.
The reference contains both descriptions and examples, for each property and method.
Your message has been sent to W3Schools.