How to replace text in a string
Short answer
The replaceAll() method replaces every occurrence of a substring:
console.log('cat and cat'.replaceAll('cat', 'dog'));Output:
dog and dogOnly the first occurrence
The replace() method with a string replaces only the first match:
console.log('cat and cat'.replace('cat', 'dog'));Output:
dog and catIgnoring case
Use a regular expression with the g (all occurrences) and i (ignore case) flags:
console.log('Hello, hello'.replace(/hello/gi, 'Hi'));Output:
Hi, HiReplacement with a function
The second argument can be a function that builds the replacement from the found text:
const text = 'Prices: 10 and 25';
console.log(text.replace(/\d+/g, (match) => `$${match}`));Output:
Prices: $10 and $25Common mistake
replaceAll() with a regular expression requires the g flag, otherwise it throws an error:
try {
'a-b-c'.replaceAll(/-/, '+');
} catch (error) {
console.log(error.name);
}
console.log('a-b-c'.replaceAll(/-/g, '+'));Output:
TypeError
a+b+cFunctions used in this recipe
- String.prototype.replaceAll — Replaces all occurrences of a substring with another string.
- String.prototype.replace — Replaces the first match (or all of them with a regex g flag).