JavaScriptStrings

String.prototype.replaceAll()

Returns a new string in which every occurrence of a pattern has been replaced with the given text or the result of a function.

Returns
A new string with every match replaced by the replacement text.
Changes the original
No
On this page

Example

#
JavaScript
const slug = 'javascript course for beginners'.replaceAll(' ', '-')
const template = 'Hi {name}! {name}, you have a new task.'

console.log(slug)
console.log(template.replaceAll('{name}', 'Mia'))
Console
javascript-course-for-beginners
Hi Mia! Mia, you have a new task.

Definition and usage

#

The replaceAll() method works like replace(), but it always replaces every match, not just the first one. With plain text, you don't need to build a regular expression with the g flag or worry about special characters.

The pattern can be a string or a regular expression, but the expression must have the g flag. Without it, the method throws a TypeError. The second argument, just like in replace(), can be text (with $&, $1 sequences) or a function.

Like all string methods, replaceAll() does not change the original, it just returns a new string.

Syntax

#
Syntax
string.replaceAll(pattern, replacement)

Parameters

#
  • pattern

    string | RegExp

    A string, or a regular expression with the g flag. Every occurrence gets replaced.
  • replacement

    string | function

    The replacement text, or a function called for every match whose result ends up in the new string.

More examples

#
Special characters treated literally
JavaScript
const version = 'v1.2.3'

console.log(version.replaceAll('.', '-'))
console.log(version.replace(/./g, '-'))
Console
v1-2-3
------

In a regular expression, a dot means any character, so /./g replaced everything. replaceAll() with a string treats the dot literally.

A regular expression requires the g flag
JavaScript
const text = 'a-b-c'

console.log(text.replaceAll(/-/g, ' + '))

try {
  text.replaceAll(/-/, ' + ')
} catch (error) {
  console.log(error.name)
}
Console
a + b + c
TypeError
A function as the replacement
JavaScript
const text = 'Learning html, css, and javascript'
const loud = text.replaceAll(/html|css|javascript/g, (tech) => tech.toUpperCase())

console.log(loud)
Console
Learning HTML, CSS, and JAVASCRIPT

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • For replacing plain text, replaceAll() is the simplest and most readable choice. Reach for a regular expression when you need a pattern, such as any digit.
  • Remember the g flag with a regular expression. Without it, you get a TypeError instead of a result.

Related entries

#

Spotted a mistake or missing an example? Write to us.