The replaceAll() method replaces all occurrences of the search string with the replacement text and returns a new string. This method does not change the original string.

Like the replace() method, you can pass a string or a regular expression as a search pattern. The replacement can be a string or a function called for each match.

const str = 'Mr. Red owns a red bike and a red car.'
const newStr = str.replaceAll(/red/gi, 'blue')

console.log(newStr)
// Mr. blue owns a blue bike and a blue car.

Note that A RegExp without the global (g) modifier will throw a TypeError: "replaceAll must be called with a global RegExp".

The replaceAll() method also accepts a function (instead of a string) as the second parameter:

const str = 'Mr. Red owns a red bike and a red car.'
const newStr = str.replace(/red/gi, match => {
  return match.toLowerCase()
})

console.log(newStr)
// Mr. red owns a red bike and a red car.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.