Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

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

ParameterTypeDescription
patternstring | RegExpWhat to replace: a string or a regular expression.
replacementstring | FunctionThe 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-c

A regular expression with the g flag replaces every match:

console.log('a-b-c'.replace(/-/g, '+'));

Output:

a+b+c

A 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: 4

Notes

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

Related recipes

In the tutorial

  • String methods — Useful string methods in JavaScript: finding a position, reading characters, padStart, repeat, split and join, method chains.

Thanks for reading!

Donate to the site — we work hard for you.