JavaScript (ES2026) reference · String Methods

JavaScript String replace() Method

Replace the first match of a string or regex (every match with the g flag) with new text or a function's result.

JavaScript (ES2026) Since ES3

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

string.replace(pattern, replacement)

Parameters

ParameterDescription
pattern A string (first occurrence only) or a regular expression.
replacement A string (may use $1, $&) or a function returning the replacement.

Return value

A new string.

Examples

First match vs all matchesTry it yourself
const s = "red, red, red";
console.log(s.replace("red", "blue"));
console.log(s.replace(/red/g, "blue"));

Output

blue, red, red
blue, blue, blue
Capture groups and a functionTry it yourself
console.log("2026-10-22".replace(/(\d+)-(\d+)-(\d+)/, "$3/$2/$1"));
console.log("price: 10".replace(/\d+/, (n) => n * 2));

Output

22/10/2026
price: 20

Version history

VersionChange
JavaScript ES3Added

In other languages

Was this page helpful?