transformation

String.prototype.replace

Returns a new string with the first match of pattern replaced. Pattern can be a string (only the first occurrence) or a RegExp (all occurrences when the g flag is set).

str.replace(pattern, replacement)

Parameters

Parameter Purpose
pattern String or RegExp to match
replacement Replacement string ($1, $&, $<name>) or function returning a string

Examples

console.log('foo foo'.replace('foo', 'bar'));

Prints 'bar foo' (only first match)

console.log('foo foo'.replace(/foo/g, 'bar'));

Prints 'bar bar'

console.log('John Smith'.replace(/(\w+)\s(\w+)/, '$2 $1'));

Prints 'Smith John'

console.log('abc123'.replace(/\d+/, m => m.length));

Prints 'abc3'

Gotcha

A string pattern only replaces the first match — use replaceAll or a /g RegExp for all. Strings are immutable; the original is unchanged.

Related methods

← All JS string methods · JS array methods