Skip to content

Working with Strings

A string is a sequence of characters, such as a name, a sentence or a file name. JavaScript gives every string a set of methods for changing case, cutting out parts, searching and joining. None of them change the original string, because strings are immutable, so each method returns a new string instead.

This page is a quick tour. The pages that follow look at each group of methods in more detail.

Most strings are written as literals, in single quotes, double quotes or backticks. Calling String() as a function converts a value to a string. Calling it with new creates a String object, which is a wrapper around the text rather than a string itself.

const fruit = 'pear';
const count = String(42);
const boxed = new String('pear');
console.log(typeof fruit, typeof count, typeof boxed);
console.log(fruit === 'pear', boxed === 'pear');

This prints:

string string object
true false

The String object fails a strict equality test against the same text, which is why new String() is best avoided. A plain literal already has every string method, because JavaScript wraps it in a temporary object whenever a method is called on it.

toUpperCase() and toLowerCase() return a new string, so the result has to be stored or used. The length property gives the number of characters.

const city = 'Leeds';
city.toUpperCase();
console.log(city);
const shout = city.toUpperCase();
console.log(shout, city.toLowerCase(), city.length);

This prints:

Leeds
LEEDS leeds 5

The first call to toUpperCase() has no effect on city, because its result is thrown away.

slice(start, end) returns the characters from start up to, but not including, end. A negative position counts back from the end of the string. indexOf() returns the position of the first match, and includes() answers whether there is a match at all.

const fileName = 'report-2026.pdf';
console.log(fileName.slice(0, 6));
console.log(fileName.slice(7, 11));
console.log(fileName.slice(-3));
console.log(fileName.indexOf('-'));
console.log(fileName.includes('2026'));

This prints:

report
2026
pdf
6
true

Older code often uses substring() or substr() for the same job. substr() is deprecated, and substring and substr explains how both differ from slice(). Searching is covered in indexOf and lastIndexOf and in startsWith, endsWith and finding strings.

A template literal, written in backticks, puts values into a string with ${}. The join() method does the same job for the items of an array.

const first = 'Ada';
const last = 'Lovelace';
console.log(`${first} ${last}`);
console.log([first, last].join(' '));

This prints:

Ada Lovelace
Ada Lovelace

String concatenation compares these with the + operator and the concat() method. MDN keeps a full list of methods on its String reference page.

Steve Griffith covers this topic in his video Working with Strings in JavaScript.