String.prototype.replace()

Returns a new string with the first match of a pattern replaced.

Since ES1 Spec ↗

Syntax

str.replace(pattern, replacement)

Parameters

NameTypeRequiredDescription
pattern string | RegExp Yes A substring or regular expression to match. A string matches only the first occurrence; a regex with the g flag matches all.
replacement string | Function Yes Replacement string (supports $1, $&, $`, etc.) or a function returning the replacement.

Returns

string — A new string with the replacement applied.

Examples

console.log('a-b-c'.replace('-', '+'));
Output
a+b-c
console.log('a-b-c'.replace(/-/g, '+'));
Output
a+b+c

Notes

With a string pattern only the first occurrence is replaced - use a /g regex or `replaceAll` for all. In the replacement string, `$$` inserts a literal `$`. Does not mutate the original string.

Browser & runtime support

EnvironmentSince version
chrome 1.0
firefox 1.0
safari 1.0
edge 12
node 0.10

See also