JavaScript String replaceAll()

Definition and usage

replaceAll() This method is used to search for a specified value or regular expression in a string.

replaceAll() This method returns a new string with all matches replaced.

replaceAll() This method does not change the original string.

replaceAll() This method was introduced in JavaScript 2021.

replaceAll() This method is not available in Internet Explorer.

Note

If the parameter is a regular expression, the global flag must be set (g),否则会抛出 TypeError。

For more information about regular expressions, please see:

Regular expression tutorial

Regular expression reference

Instance

Example 1

text = text.replaceAll("Cats","Dogs");
text = text.replaceAll("cats","dogs");

Try it yourself

Example 2

text = text.replaceAll(/Cats/g,"Dogs");
text = text.replaceAll(/cats/g,"dogs");

Try it yourself

Example 2

Global, case-insensitive replacement:

let text = "Mr Blue has a blue house and a blue car";
let result = text.replaceAll(/blue/gi, "red");

Try it yourself

Example 3

Use a function to return the replaced text:

let text = "Mr Blue has a blue house and a blue car";
let result = text.replaceAll(/blue|house|car/gi, function (x) {
  return x.toUpperCase();
});

Try it yourself

Syntax

string.replaceAll(searchValue, newValue)

Parameter

Parameter Beskrivelse
searchValue Required. The value to search for or a regular expression.
newValue Required. The new value to replace. It can be a JavaScript function.

Return value

Type Beskrivelse
String Returnerer en ny streng, hvor alle matchende værdier er blevet erstattet.