JavaScript String replace()
Examples
Replace Microsoft:
let text = "Visit Microsoft!";
let result = text.replace("Microsoft", "W3Schools");
Try it Yourself »
A global replacement:
let text = "Mr Blue has a blue house and a blue car";
let result = text.replace(/blue/g, "red");
Try it Yourself »
More examples below.
Description
The replace()
method searches a string for a value or a regular expression.
The replace()
method returns a new string with the value(s) replaced.
The replace()
method does not change the original string.
Note
If you replace a value, only the first instance will be replaced. To replace all instances, use a regular expression with the g modifier set.
Read more about regular expressions in our:
See Also:
The replaceAll() Method - replaces all matches
Syntax
string.replace(searchValue, newValue)
Parameters
Parameter | Description |
searchValue | Required. The value, or regular expression, to search for. |
newValue | Required. The new value (to replace with). |
Return Value
Type | Description |
A string | A new string where the specified value(s) has been replaced. |
More Examples
A global, case-insensitive replacement:
let text = "Mr Blue has a blue house and a blue car";
let result = text.replace(/blue/gi, "red");
Try it Yourself »
A function to return the replacement text:
let text = "Mr Blue has a blue house and a blue car";
let result = text.replace(/blue|house|car/gi, function (x) {
return x.toUpperCase();
});
Try it Yourself »
Browser Support
replace()
is an ECMAScript1 (JavaScript 1997) feature.
It is supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | Yes |