Skip to main content
Version: 3.28.0

String.prototype.replace()

The replace() method returns a new string with one, some, or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function called for each match. If pattern is a string, only the first occurrence will be replaced. The original string is left unchanged.

Syntax

replace(pattern, replacement)

Parameters

  • pattern
    • : Can be a string or an object with a Symbol.replace method — the typical example being a regular expression. Any value that doesn't have the Symbol.replace method will be coerced to a string.
  • replacement
    • : Can be a string or a function.
      • If it's a string, it will replace the substring matched by pattern. A number of special replacement patterns are supported; see the Specifying a string as the replacement section below.
      • If it's a function, it will be invoked for every match and its return value is used as the replacement text. The arguments supplied to this function are described in the Specifying a function as the replacement section below.

Return value

A new string, with one, some, or all matches of the pattern replaced by the specified replacement.

Description

This method does not mutate the string value it's called on. It returns a new string.

A string pattern will only be replaced once. To perform a global search and replace, use a regular expression with the g flag, or use replaceAll() instead.

If pattern is an object with a Symbol.replace method (including RegExp objects), that method is called with the target string and replacement as arguments. Its return value becomes the return value of replace(). In this case the behavior of replace() is entirely encoded by the @@replace method — for example, any mention of "capturing groups" in the description below is actually functionality provided by RegExp.prototype[@@replace].

If the pattern is an empty string, the replacement is prepended to the start of the string.

"xxx".replace("", "_"); // "_xxx"

A regexp with the g flag is the only case where replace() replaces more than once. For more information about how regex properties (especially the sticky flag) interact with replace(), see RegExp.prototype[@@replace]().

Specifying a string as the replacement

The replacement string can include the following special replacement patterns:

PatternInserts
$$Inserts a "$".
$&Inserts the matched substring.
$`Inserts the portion of the string that precedes the matched substring.
$'Inserts the portion of the string that follows the matched substring.
$nInserts the nth (1-indexed) capturing group where n is a positive integer less than 100.
$<Name>Inserts the named capturing group where Name is the group name.

$n and $<Name> are only available if the pattern argument is a RegExp object. If the pattern is a string, or if the corresponding capturing group isn't present in the regex, then the pattern will be replaced as a literal. If the group is present but isn't matched (because it's part of a disjunction), it will be replaced with an empty string.

"foo".replace(/(f)/, "$2");
// "$2oo"; the regex doesn't have the second group

"foo".replace("f", "$1");
// "$1oo"; the pattern is a string, so it doesn't have any groups

"foo".replace(/(f)|(g)/, "$2");
// "oo"; the second group exists but isn't matched

Specifying a function as the replacement

You can specify a function as the second parameter. In this case, the function will be invoked after the match has been performed. The function's result (return value) will be used as the replacement string.

Note: The above-mentioned special replacement patterns do not apply for strings returned from the replacer function.

The function has the following signature:

function replacer(match, p1, p2, /* …, */ pN, offset, string, groups) {
return replacement;
}

The arguments to the function are as follows:

  • match
    • : The matched substring. (Corresponds to $& above.)
  • p1, p2, …, pN
    • : The nth string found by a capture group (including named capturing groups), provided the first argument to replace() is a RegExp object. (Corresponds to $1, $2, etc. above.) For example, if the pattern is /(\a+)(\b+)/, then p1 is the match for \a+, and p2 is the match for \b+. If the group is part of a disjunction (e.g. "abc".replace(/(a)|(b)/, replacer)), the unmatched alternative will be undefined.
  • offset
    • : The offset of the matched substring within the whole string being examined. For example, if the whole string was 'abcd', and the matched substring was 'bc', then this argument will be 1.
  • string
    • : The whole string being examined.
  • groups
    • : An object whose keys are the used group names, and whose values are the matched portions (undefined if not matched). Only present if the pattern contains at least one named capturing group.

The exact number of arguments depends on whether the first argument is a RegExp object — and, if so, how many capture groups it has.

The following example will set newString to 'abc - 12345 - #$*%':

function replacer(match, p1, p2, p3, offset, string) {
// p1 is non-digits, p2 digits, and p3 non-alphanumerics
return [p1, p2, p3].join(" - ");
}
const newString = "abc12345#$*%".replace(/([^\d]*)(\d*)([^\w]*)/, replacer);
console.log(newString); // abc - 12345 - #$*%

The function will be invoked multiple times for each full match to be replaced if the regular expression in the first parameter is global.