Favorites

JavaScript String.prototype.replace() Method

☕
Enjoying this site?

Help keep it running with a small coffee donation. Every bit of support is appreciated!

Buy us a coffee
String.prototype.replace()
JavaScript String Instance methodThis method is supported by all modern browsers.
Updated 28th November 2026

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 $1 and $&, 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

const s = 'cat, cat, cat';
console.log(s.replace('cat', 'dog'));
console.log(s.replace(/cat/g, 'dog'));

console.log('2026-11-28'.replace(/(\d+)-(\d+)-(\d+)/, '$3/$2/$1'));
console.log('price: 10'.replace(/\d+/, n => n * 2));

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.

This method is supported by all modern browsers.

Desktop

Chrome
Edge
Firefox
Opera
Safari

Tablets & Mobile

Chrome Android
Firefox Android
Opera Android
Safari iOS
Samsung Internet
Android WebView
-
Supported Unknown Not supported
☕
Enjoying this site?

Help keep it running with a small coffee donation. Every bit of support is appreciated!

Buy us a coffee