JavaScript String replaceAll()
- Forrige side replace()
- Næste side search()
- Gå tilbage til niveauet over JavaScript String Reference Manual
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:
Instance
Example 1
text = text.replaceAll("Cats","Dogs"); text = text.replaceAll("cats","dogs");
Example 2
text = text.replaceAll(/Cats/g,"Dogs"); text = text.replaceAll(/cats/g,"dogs");
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");
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(); });
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. |
- Forrige side replace()
- Næste side search()
- Gå tilbage til niveauet over JavaScript String Reference Manual