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
Syntax
string.replace(pattern, replacement)
Parameters
| Parameter | Description |
|---|---|
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
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
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
| Version | Change |
|---|---|
| JavaScript ES3 | Added |
In other languages
str.replace()· Python
Related
string.replaceAll()· Replace every occurrence of a string (or regex with the g flag) with new text, without writing a regex.string.match()· Match the string against a regular expression and return the matches (all of them with the g flag) or null.string.split()· Split a string into an array of substrings at each separator (a string or regex), with an optional limit.- JavaScript Strings · tutorial
- JavaScript String Methods · tutorial