JavaScript String.prototype.replace() Method
The replace() method returns a new string with the first match of a string or regular expression replaced. Use a regex with the g flag, or replaceAll(), to replace every match.
Description
The replace() method returns a new string with some or all matches of a pattern replaced. When the pattern is a string, only the first occurrence is replaced; to replace them all, use a regular expression with the g flag or replaceAll().
The replacement can include special sequences: $& for the matched text, $1, $2 for capture groups and $<name> for named groups. It can also be a function, called for each match, whose return value is used as the replacement. The original string is never changed.
In the replacement string, $$ inserts a literal dollar sign, which matters when inserting prices or other text that might contain $. Replacement functions receive the match, each capture group, the position and the whole string as arguments, so they can make decisions based on context. A function replacement avoids the special $ patterns entirely.
Syntax
string.replace(pattern, replacement)Parameters
- patternA string or regular expression to find. A string only matches its first occurrence.
- replacementThe new text, which can use special patterns such as
$1and$&, or a function that returns the new text for each match.
Return Value
A new string with the match (or matches, for a regex with the g flag) replaced.
Example
Browser Support
The following information will show you the current browser support for the String.prototype.replace() method. Hover over a browser icon to see the version that first introduced support for this method.
Desktop





Tablets & Mobile





