JavaScript String
Object
The String object is used to manipulate a sequence of characters.
JavaScript Strings
A string is used to store a series of characters like "John Doe".
A string can be enclosed in single or double quotes:
Example
You can access any character in a string by using its position (index):
Example
String indexes start from zero, so the first character is at [0], the second character is at [1], and so on.
You can use quotes inside a string, as shown in the following example:
Example
var answer = "It's alright";
var answer = "He is called 'Johnny'";
var answer = 'He is called "Johnny"';
Alternatively, you can use the escape character () to include quotes in a string:
Example
var answer = 'It\'s alright';
var answer = "He is called \"Johnny\"";
String
The String object uses the length property to calculate the length of a string:
Example
Finding a String in a String
The indexOf() method is used to locate the first occurrence of a specified character in a string:
Example
If the character is not found, the function returns -1.
The lastIndexOf() method starts searching from the end of the string.
Content Matching
The match() function is used to find a specific character in a string and returns it if found.
Example
Replacing Content
The replace() method is used to replace some characters with others in a string.
Example
Converting to Upper and Lower Case
Strings are converted to upper and lower case using the functions toUpperCase() and toLowerCase():
Example
Converting a String to an Array
A string is converted to an array using the split() function:
Example
Special Characters
In JavaScript, special symbols such as apostrophes and quotes can be inserted using a backslash ().
Consider the following JavaScript code:
In JavaScript, strings start and end with single or double quotes. This means the string will be cut off as: We are the so-called
To solve this issue, use a backslash to escape the quotes:
JavaScript will output the correct text string: We are the so-called "Vikings" from the north.
The following table lists other special characters that can be escaped using a backslash:
Code | Output |
---|---|
\' | Single quote |
\" | Double quote |
\ | Backslash |
\n | New line |
\r | Carriage return |
\t | Tab |
\b | Backspace |
\f | Form feed |
String Properties and Methods
Properties:
- length
- prototype
- constructor
Methods:
- charAt()
- charCodeAt()
- concat()
- fromCharCode()
- indexOf()
- lastIndexOf()
- match()
- replace()
- search()
- slice()
- split()
- substr()
- substring()
- toLowerCase()
- toUpperCase()
- valueOf()
For more methods and properties, refer to: JavaScript String Object