Skip to content

JavaScript Strings

JavaScript strings are used for storing and manipulating textual data.

A JavaScript string is a sequence of zero or more characters, like “Hello, World!” or ‘JavaScript is fun!’.

Strings can be created using single quotes ('...'), double quotes ("..."), or backticks (template literals: `...`):

const carName1 = "Volvo XC60";
const carName2 = 'Volvo XC60';
const carName3 = `Volvo XC60`; // Template literal

You can use quotes inside a string, as long as they don’t match the quotes surrounding the string. If they do match, you must escape them:

const answer1 = "It's alright"; // Single quote inside double quotes
const answer2 = 'He is called "Johnny"'; // Double quotes inside single quotes
const answer3 = "He is called \"Johnny\""; // Escaping double quotes
const answer4 = 'It\\'s alright'; // Escaping single quote

The length property of a string returns the number of characters in it (its length):

const txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const len = txt.length; // len will be 26

To include special characters within a string, you use the backslash (\) escape character.

This is necessary when you want to include a quote character that is the same as the one delimiting the string, or for characters that are not directly typable or have special meaning.

Common escape sequences:

SequenceRepresents
’Single quote (’)
“Double quote (”)
\Backslash ()
\nNew line
\rCarriage return (often used with \n for CRLF line endings)
\tTab
\bBackspace (rarely used in modern web contexts)
\fForm feed (rarely used in modern web contexts)

Example:

const message = "This string contains a \"quoted text\" and a new line character.\nSee? This is on a new line.";
console.log(message);

ES6 introduced template literals, which provide an enhanced way to work with strings. They are enclosed by backticks (`) instead of single or double quotes.

Key features of template literals:

  • String Interpolation: Easily embed expressions (variables, function calls, etc.) directly within the string using ${expression}.
  • Multi-line Strings: Strings can span multiple lines without needing special escape characters like \n.

Example of interpolation:

const name = "Alice";
const age = 30;
const greeting = `Hello, my name is ${name} and I am ${age} years old.`;
// greeting will be "Hello, my name is Alice and I am 30 years old."

Example of multi-line string:

const poem = `The quick brown fox
jumps over
the lazy dog.`;
console.log(poem);

This is generally the preferred way to create multi-line strings or strings with embedded variables in modern JavaScript.

Normally, JavaScript strings are primitive values, created from literals (e.g., const firstName = "John";).

However, strings can also be defined as objects using the new String() constructor (e.g., const firstName = new String("John");).

const x = "John"; // typeof x is "string" (primitive)
const y = new String("John"); // typeof y is "object"
console.log(x === y); // false (different types)
console.log(x == y); // true (values are the same, loose equality)
Warning: Do not create strings as objects using new String(). It significantly slows down execution speed, complicates comparisons, and leads to unexpected behavior. Always use string literals for creating strings.

Comparing string objects is tricky:

const a = new String("John");
const b = new String("John");
console.log(a === b); // false (they are different objects in memory)
console.log(a == b); // false (objects are compared by reference, not value)

Although string literals are primitive values, JavaScript temporarily wraps them with a String object when you try to access a property (like length) or call a method on them. This allows you to use object-like features with primitive strings seamlessly.

PropertyDescription
lengthReturns the number of characters in the string.

String methods return a new string or other value; they do not modify the original string (strings are immutable).

MethodDescription
charAt(index)Returns the character at the specified index.
charCodeAt(index)Returns the Unicode value of the character at the specified index.
concat(str1, str2, …, strN)Joins two or more strings and returns a new combined string.
includes(searchValue, position?)Checks if a string contains another string, returning true or false. Case-sensitive.
startsWith(searchValue, position?)Checks if a string begins with the characters of a specified string, returning true or false.
endsWith(searchValue, length?)Checks if a string ends with the characters of a specified string, returning true or false.
indexOf(searchValue, fromIndex?)Returns the index of the first occurrence of a specified value in a string. Returns -1 if not found.
lastIndexOf(searchValue, fromIndex?)Returns the index of the last occurrence of a specified value in a string. Returns -1 if not found.
match(regexp)Searches a string for a match against a regular expression, and returns the matches as an Array object.
matchAll(regexp)Returns an iterator of all results matching a string against a regular expression, including capturing groups.
replace(searchValue, newValue)Searches a string for a value (or regular expression) and returns a new string with some or all matches replaced. newValue can be a string or a function.
replaceAll(searchValue, newValue)Returns a new string with all occurrences of searchValue replaced by newValue.
search(regexp)Searches a string for a value (regular expression) and returns the position of the match. Returns -1 if no match.
slice(startIndex, endIndex?)Extracts a section of a string and returns it as a new string. endIndex is not included.
split(separator?, limit?)Splits a string into an array of substrings based on the specified separator.
substring(startIndex, endIndex?)Extracts characters from a string between two specified indices. If startIndex > endIndex, they are swapped.
toLowerCase()Converts a string to lowercase letters.
toUpperCase()Converts a string to uppercase letters.
trim()Removes whitespace from both ends of a string.
trimStart() (or trimLeft())Removes whitespace from the beginning of a string.
trimEnd() (or trimRight())Removes whitespace from the end of a string.
padStart(targetLength, padString?)Pads the current string from the start with another string so the resulting string reaches the given length.
padEnd(targetLength, padString?)Pads the current string from the end with another string so the resulting string reaches the given length.
toString()Returns the string itself (can be used to convert a String object back to a primitive string).
valueOf()Returns the primitive value of a String object.

Note: substr(startIndex, length) is considered a legacy feature. Use substring() or slice() instead.