JavaScript Strings
In JavaScript, the strings are used for storing and manipulating text. On this page, you will learn how to create strings, use them and make comparisons.
In JavaScript, strings are used for storing and manipulating text. Unlike some other languages, JavaScript has no separate type for a single character — a character is simply a string of length 1. The internal format of every string is always UTF-16, which is why each character maps to a numeric code (more on that below).
A string represents zero or more characters written inside quotes. Strings are one of JavaScript's primitive data types, but they expose many useful methods — see methods of primitives for why a primitive can have methods at all.
On this page you'll learn how to create strings (with quotes, double quotes, and backticks), use special characters, read a string's length, access individual characters, extract substrings, change case, search inside a string, and compare strings correctly.
Popular String Functions
| Function | Description |
|---|---|
charAt(index) | Returns the character at the specified index. |
charCodeAt(index) | Returns the Unicode of the character at the specified index. |
concat(...strings) | Concatenates the string arguments to the calling string and returns a new string. |
includes(searchString, position) | Determines whether the calling string contains the searchString. |
indexOf(searchValue, fromIndex) | Returns the index of the first occurrence of searchValue in the string, starting the search at fromIndex. Returns -1 if the value is not found. |
lastIndexOf(searchValue, fromIndex) | Returns the index of the last occurrence of searchValue within the calling string, searching backwards from fromIndex. Returns -1 if the value is not found. |
match(regexp) | Retrieves the matches when matching a string against a regular expression. |
matchAll(regexp) | Returns an iterator of all results matching a string against a regular expression, including capturing groups. |
repeat(count) | Returns a new string consisting of the calling string repeated count times. |
replace(searchFor, replaceWith) | Replaces the first match of a substring or pattern with a replacement string. |
replaceAll(searchFor, replaceWith) | Replaces all matches of a substring or pattern with a replacement string. |
search(regexp) | Searches the string for a match against a regular expression, and returns the index of the match. |
slice(startIndex, endIndex) | Extracts a section of a string and returns it as a new string, without modifying the original string. |
split(separator, limit) | Divides a string into an ordered list of substrings, puts these substrings into an array, and returns the array. The division is done by searching for a pattern; where the pattern is provided as the first parameter in the method's call. |
startsWith(searchString, position) | Determines whether the calling string begins with the characters of searchString. |
substring(startIndex, endIndex) | Returns the part of the string between the start and end indexes, or to the end of the string. |
toLowerCase() | Returns the calling string value converted to lowercase. |
toUpperCase() | Returns the calling string value converted to uppercase. |
trim() | Trims whitespace from both ends of the string. |
trimStart() or trimLeft() | Trims whitespace from the beginning of the string. |
trimEnd() or trimRight() | Trims whitespace from the end of the string. |
valueOf() | Returns the primitive value of a String object. |
About Quotes
JavaScript gives you three ways to quote a string: single quotes, double quotes, and backticks:
let single = 'single-quoted';
let double = "double-quoted";
let backticks = `backticks`;Single and double quotes behave identically — pick one style and stay consistent. Backticks are different: they support template literals, letting you embed any expression directly into the string by wrapping it in ${…}:
The expression inside ${…} can be anything — a variable, a calculation, or a function call:
Another key advantage of backticks is that they let a string span multiple lines:
Single and double quotes cannot span multiple lines on their own. Putting a raw line break inside them is a syntax error:
let guestList = "Guests: // SyntaxError: Invalid or unexpected token
* John ";Single and double quotes predate backticks, so backticks are the more capable, modern choice.
You can also put a "template function" (a tagged template) before the first backtick:
func`string`;The func function is called automatically and receives the literal string parts together with the embedded expressions, so it can process them. This is how libraries implement custom templating, but in everyday code it's rarely needed.
Special Characters
You can create multiline output from single or double quoted strings with the help of \n (the newline character), like this:
There exist other less common special characters.
Find some of them in the list below:
- \', \" these special characters are used for quotes
- \r - carriage return. This character is now used alone. A combination of two characters \r\n is used for representing a line break in Windows text files.
- \\ - backslash
- \t - tab
- \xXX - unicode character with a particular hexadecimal unicode XX
- \uXXXX - this is unicode symbol with the hex code XXXX in UTF-16 encoding. It must include exactly 4 digits.
Here are examples with Unicode escapes:
Every special character begins with a backslash, which is why the backslash is also called the escape character. You can use it to put a matching quote inside a string:
The backslash exists only to tell JavaScript how to read the source code — it disappears once the string is created, so it is not stored in memory. When you actually need a backslash in the string, double it:
The String Length
The length property gives you the number of characters in a string:
Note that \n is a single special character, so the length is 7 (W3Docs plus one newline), not 8.
A common mistake is calling str.length() instead of reading str.length. length is a property, not a method — adding () throws a "not a function" error.
Accessing Characters
Square brackets [pos] are the usual way to get the character at a given position. You can also call the str.charAt(pos) method. Positions are zero-based, so the first character is at index 0:
The one difference: if no character exists at the position, str[pos] returns undefined while str.charAt(pos) returns an empty string ''. Modern code generally prefers square brackets; charAt is rarely used today.
Strings are Changeless
Strings in JavaScript are immutable — you cannot change a character in place. The assignment below silently fails (in strict mode it throws), so the original character is unchanged:
Instead, build a whole new string and assign it back to the variable:
Case Changing
Two methods change the case of a whole string — toUpperCase() and toLowerCase():
To lowercase just a single character, first index into the string, then call the method on that character:
Looking for a Substring
There are several ways to search for a substring inside a string.
str.indexOf
str.indexOf(substr, pos) searches for substr inside str, optionally starting from position pos. It returns the index of the first match, or -1 if there is no match:
str.lastIndexOf
str.lastIndexOf(substr, pos) works like indexOf, but searches from the end of the string toward the beginning, returning the index of the last match.
A common gotcha: don't use indexOf directly in an if test. Because a match at position 0 is falsy, this looks correct but is wrong:
Always compare against -1 instead:
includes, startsWith, endsWith
The more modern str.includes(substr, pos) returns true or false depending on whether str contains substr. Use it when you only need to know whether a match exists, not where:
Its optional second argument is the position to start searching from:
str.startsWith(substr) and str.endsWith(substr) are closely related — they test the beginning and the end of the string:
Getting a Substring
JavaScript has three methods for getting a substring: slice, substring, and substr. In modern code, slice is the recommended one — it is the most flexible and substr is considered legacy.
str.slice(start, end)
slice returns the part of the string from start up to (but not including) end:
If the second argument is omitted, slice runs to the end of the string:
You can also use negative values, which count from the end:
str.substring(start, end)
substring returns the part of the string between start and end. It is much like slice, with one notable difference: if start is greater than end, substring swaps the two arguments, whereas slice returns an empty string. It also treats negative arguments as 0:
str.substr(start, length)
substr returns the part of the string starting at start with a given length. Unlike the others, its second argument is a length, not an end position. This method is legacy — prefer slice in new code.
A negative start counts from the end:
Comparison of the Strings
The <, >, <=, and >= operators compare strings character-by-character, using each character's Unicode code (see comparison operators for the general rules). Two consequences often surprise newcomers:
- A lowercase letter is "greater than" an uppercase one, because lowercase letters have higher codes:
- Letters with diacritical marks sort "out of order" — they sit outside the basic A–Z range, so they compare as larger:
Because of this, the comparison operators are fine for sorting strictly by code, but not for human-friendly alphabetical order. For locale-aware comparison, use str.localeCompare(other), which returns a negative number, 0, or a positive number:
Characters and their codes
Since strings are UTF-16, every character has a numeric code. str.codePointAt(pos) returns the code of the character at position pos:
String.fromCodePoint(code) does the reverse — it builds a character from a numeric code:
You can also insert a character by its code in a string literal using \u followed by the hex code:
As a fuller example, here is a string built from the characters with codes 65..220:
The capital letters come first, then several special characters, and the output ends around Ö.
Related Topics
- JavaScript data types — where strings fit among the primitives.
- Methods of primitives — how a primitive string can have methods.
- Numbers — the companion primitive type.
- Comparison operators — the full comparison rules.
- Array methods — useful after
split()turns a string into an array.