Strings are primitive types in JavaScript that can be created with single quotes or double quotes. There is no difference. It's only a matter of style. ES2015 introduced two new string features: template literals and multiline strings.
Multiline strings can be created by adding a backslash at the end of each line:
const line = "Multiline strings can be \
reated adding a backslash \
at the end of each line";
Template literals are strings created with backticks. They allow the inclusion of JavaScript expressions inside the ${} placeholders. The result is concatenated as a single string:
const template = `The square root of 2 is ${Math.sqrt(2)}`;
If you need to use a special character in a string, such as a double quote in a double-quoted string or a backslash, you need to precede it with a backslash:
const s = "This is a backslash \\ and this is a double quote \"";
There are several methods for string manipulation. They all return new strings or other types. No methods modify the original strings:
Method |
Description |
Example |
startsWith(s) |
Returns true if the string starts with the string passed as a parameter. |
const s = "This is a test string" |
endsWith(s) |
Returns true if string ends with the string passed as a parameter. |
const s = "This is a test string" |
substring(s,e) |
Returns a substring between start (incl.) and end indexes (not incl.). |
const k = "Aardvark" |
split(regx) split(delim) |
Splits a string by a delimiter character or a regular expression and returns an array. |
const result = s.split(" "); |
indexOf() |
Returns the index of the first occurrence of a substring. |
const k = "Aardvark" |
lastIndexOf() |
Returns the index of the last occurrence of a substring. |
const k = "Aardvark" |
charAt(i) |
Returns char at index i. Also supported as ‘string'[i]. |
const k = "Aardvark" |
trim() |
Removes whitespace from both ends of a string. |
const text = " data " |
match(regx) |
Returns an array as the result of matching a regular expression against the string. |
const k = "Aardvark" |
replace(regx,r) replace(s,t) |
Returns a new string replacing the matching of regexp applied to the string with a replacement or all occurrences of the source string with a target string. |
const k = "Aardvark" |