String.prototype.replace
Replaces the first match (or all of them with a regex g flag).
Available since: ES3
Syntax
str.replace(pattern, replacement)Parameters
| Parameter | Type | Description |
|---|---|---|
| pattern | string | RegExp | What to replace: a string or a regular expression. |
| replacement | string | Function | The replacement: a string or a function that returns it. |
Return value
stringA new string with the replacement.
Examples
A string pattern is replaced only once:
console.log('a-b-c'.replace('-', '+'));Output:
a+b-cA regular expression with the g flag replaces every match:
console.log('a-b-c'.replace(/-/g, '+'));Output:
a+b+cA function instead of a replacement string:
const text = 'price: 10, tax: 2';
console.log(text.replace(/\d+/g, (n) => n * 2));Output:
price: 20, tax: 4Notes
The original string is not changed. To replace every occurrence of a plain string use replaceAll().
In the replacement string $1, $2 insert regex groups and $& inserts the whole match.
See also
- String.prototype.replaceAll — Replaces all occurrences of a substring with another string.
- RegExp — A regular expression — a pattern for finding and replacing text.
- String.prototype.split — Splits a string into an array by a separator.
Related recipes
In the tutorial
- String methods — Useful string methods in JavaScript: finding a position, reading characters, padStart, repeat, split and join, method chains.