Skip to content

Find and Replace String Methods

replace(pattern, replacement) returns a new string with a match replaced. Given plain text as the pattern, it replaces only the first match. replaceAll() replaces every match. Neither changes the original string, because strings are immutable, so the result has to be stored.

const note = 'Buy milk. Buy bread. Buy eggs.';
const updated = note.replace('Buy', 'Get');
console.log(updated);
console.log(note);
console.log(note.replaceAll('Buy', 'Get'));

This prints:

Get milk. Buy bread. Buy eggs.
Buy milk. Buy bread. Buy eggs.
Get milk. Get bread. Get eggs.

note is unchanged after the call to replace(). There is also no need to check with indexOf() or includes() before replacing, because when nothing matches, the methods return an unchanged copy of the string.

replaceAll() arrived in ES2021. Older code replaces every match with a loop of replace() calls, or with a regular expression that has the g flag, and both can be replaced with replaceAll().

A regular expression as the pattern allows flags. The g flag replaces every match and the i flag ignores case.

const text = 'Colour, colour, COLOUR';
console.log(text.replace(/colour/i, 'color'));
console.log(text.replace(/colour/gi, 'color'));
try {
text.replaceAll(/colour/i, 'color');
} catch (error) {
console.log(`${error.name}: ${error.message}`);
}

This prints:

color, colour, COLOUR
color, color, color
TypeError: String.prototype.replaceAll called with a non-global RegExp argument

replaceAll() insists on the g flag when given a regular expression, so that the call cannot silently replace only one match.

The replacement can be a function. It is called once for each match, with the matched text as its first argument, and its return value is put in place of the match. A replacement string can refer to the match too, through special patterns: $& is the whole match, and $1, $2 and so on are the capture groups in brackets.

const menu = 'Tea 2.5, cake 3, soup 4.25';
console.log(menu.replace(/\d+(\.\d+)?/g, (amount) => `£${Number(amount).toFixed(2)}`));
console.log('cat and dog'.replace(/cat|dog/g, '[$&]'));
console.log('Smith, Jane'.replace(/(\w+), (\w+)/, '$2 $1'));

This prints:

Tea £2.50, cake £3.00, soup £4.25
[cat] and [dog]
Jane Smith

A pitfall: dollar signs in the replacement

Section titled “A pitfall: dollar signs in the replacement”

The special patterns apply even when the pattern is plain text, so a replacement string that happens to contain $& or $1 does not come out as typed. This matters when the replacement comes from a user or from data. Returning the text from a function avoids it, because the return value of a function is used exactly as it is.

const template = 'Total: AMOUNT';
const amount = '$&5';
console.log(template.replace('AMOUNT', amount));
console.log(template.replace('AMOUNT', () => amount));

This prints:

Total: AMOUNT5
Total: $&5

Writing $$ in a replacement string also gives a single $. Find and replace strings 2 applies these methods to text on a web page, and MDN lists every special pattern on its replace page.

Steve Griffith covers this topic in his video String Methods for Find and Replace.