Encodera

Thanks for reading!

Donate to the site — we work hard for you.

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 dog

Only 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 cat

Ignoring 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, Hi

Replacement 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 $25

Common 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+c

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.