JavaScript replaceAll() method
Example
In this example, we replace all "Microsoft" with "Runoob":
var
str
=
"
Visit Microsoft! Visit Microsoft!
"
;
var
n
=
str
.
replaceAll
(
"
Microsoft
"
,
"
Runoob
"
)
;
n Output result:
Visit Runoob!Visit Runoob!
Try it »
Definition and Usage
The replaceAll() method replaces some characters with others in a string, or replaces a substring that matches a regular expression, replacing all matched substrings.
If you want to learn more about regular expressions, please see our:RegExp Tutorial and our RegExp Object Reference Manual.
This method does not change the original string.
Browser support

IE browser on PC does not support this function.
Syntax
const newStr = str.replaceAll(regexp|substr, newSubstr|function)
Parameter value
| Parameters | Description |
|---|---|
| regexp|substr | Required. Specifies a substring or a RegExp object for the pattern to replace. |
| Note that if this value is a string, it is treated as a literal text pattern to search for, rather than being first converted to a RegExp object. When using a regex, you must set the global ("g") flag, otherwise a TypeError is thrown: "replaceAll must be called with a global RegExp". | |
| newSubstr|function | Required. A string value. Specifies the replacement text or a function that produces it. |
Return Value
| Type | Description |
|---|---|
| String | A new string resulting from replacing all matches of regexp with newSubstr. |
Technical Details
| JavaScript version: | 1.2 |
|---|
More examples
Example
Perform a global replacement:
var
str
=
"
Mr Blue has a blue house and a blue car
"
;
var
n
=
str
.
replaceAll
(
/
blue
/
ig
,
"
red
"
)
;
n Output result:
Mr red has a red house and a red car.
Try it »
JavaScript String object