Movatterモバイル変換


[0]ホーム

URL:


MDN Web Docs

String.prototype.replace()

BaselineWidely available

Thereplace() method ofString values returns a new string with one, some, or all matches of apattern replaced by areplacement. Thepattern can be a string or aRegExp, and thereplacement can be a string or a function called for each match. Ifpattern is a string, only the first occurrence will be replaced. The original string is left unchanged.

Try it

const paragraph = "I think Ruth's dog is cuter than your dog!";console.log(paragraph.replace("Ruth's", "my"));// Expected output: "I think my dog is cuter than your dog!"const regex = /dog/i;console.log(paragraph.replace(regex, "ferret"));// Expected output: "I think Ruth's ferret is cuter than your dog!"

Syntax

js
replace(pattern, replacement)

Parameters

pattern

Can be a string or an object with aSymbol.replace method — the typical example being aregular expression. Any value that doesn't have theSymbol.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 bypattern. A number of special replacement patterns are supported; see theSpecifying 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 theSpecifying 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 theg flag, or usereplaceAll() instead.

Ifpattern is an object with aSymbol.replace method (includingRegExp objects), that method is called with the target string andreplacement as arguments. Its return value becomes the return value ofreplace(). In this case the behavior ofreplace() is entirely encoded by the[Symbol.replace]() method — for example, any mention of "capturing groups" in the description below is actually functionality provided byRegExp.prototype[Symbol.replace]().

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

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

A regexp with theg flag is the only case wherereplace() replaces more than once. For more information about how regex properties (especially thesticky flag) interact withreplace(), seeRegExp.prototype[Symbol.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 thenth (1-indexed) capturing group wheren is a positive integer less than 100.
$<Name>Inserts the named capturing group whereName is the group name.

$n and$<Name> are only available if thepattern argument is aRegExp object. If thepattern 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.

js
"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 donot apply for strings returned from the replacer function.

The function has the following signature:

js
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

Thenth string found by a capture group (including named capturing groups), provided the first argument toreplace() is aRegExp object. (Corresponds to$1,$2, etc. above.) For example, if thepattern is/(\a+)(\b+)/, thenp1 is the match for\a+, andp2 is the match for\b+. If the group is part of a disjunction (e.g.,"abc".replace(/(a)|(b)/, replacer)), the unmatched alternative will beundefined.

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 be1.

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 thepattern contains at least one named capturing group.

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

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

js
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.

Examples

Defining the regular expression in replace()

In the following example, the regular expression is defined inreplace() and includes the ignore case flag.

js
const str = "Twas the night before Xmas...";const newStr = str.replace(/xmas/i, "Christmas");console.log(newStr); // Twas the night before Christmas...

This logs'Twas the night before Christmas...'.

Note:Seethe regular expression guide for more explanations about regular expressions.

Using the global and ignoreCase flags with replace()

Global replace can only be done with a regular expression. In the following example, the regular expression includes theglobal and ignore case flags which permitsreplace() to replace each occurrence of'apples' in the string with'oranges'.

js
const re = /apples/gi;const str = "Apples are round, and apples are juicy.";const newStr = str.replace(re, "oranges");console.log(newStr); // oranges are round, and oranges are juicy.

This logs'oranges are round, and oranges are juicy'.

Switching words in a string

The following script switches the words in the string. For the replacement text, the script usescapturing groups and the$1 and$2 replacement patterns.

js
const re = /(\w+)\s(\w+)/;const str = "Maria Cruz";const newStr = str.replace(re, "$2, $1");console.log(newStr); // Cruz, Maria

This logs'Cruz, Maria'.

Using an inline function that modifies the matched characters

In this example, all occurrences of capital letters in the string are converted to lower case, and a hyphen is inserted just before the match location. The important thing here is that additional operations are needed on the matched item before it is given back as a replacement.

The replacement function accepts the matched snippet as its parameter, and uses it to transform the case and concatenate the hyphen before returning.

js
function styleHyphenFormat(propertyName) {  function upperToHyphenLower(match, offset, string) {    return (offset > 0 ? "-" : "") + match.toLowerCase();  }  return propertyName.replace(/[A-Z]/g, upperToHyphenLower);}

GivenstyleHyphenFormat('borderTop'), this returns'border-top'.

Because we want to further transform theresult of the match before the final substitution is made, we must use a function. This forces the evaluation of the match prior to thetoLowerCase() method. If we had tried to do this using the match without a function, thetoLowerCase() would have no effect.

js
// Won't workconst newString = propertyName.replace(/[A-Z]/g, "-" + "$&".toLowerCase());

This is because'$&'.toLowerCase() would first be evaluated as a string literal (resulting in the same'$&') before using the characters as a pattern.

Replacing a Fahrenheit degree with its Celsius equivalent

The following example replaces a Fahrenheit degree with its equivalent Celsius degree. The Fahrenheit degree should be a number ending with"F". The function returns the Celsius number ending with"C". For example, if the input number is"212F", the function returns"100C". If the number is"0F", the function returns"-17.77777777777778C".

The regular expressiontest checks for any number that ends withF. The number of Fahrenheit degrees is accessible to the function through its second parameter,p1. The function sets the Celsius number based on the number of Fahrenheit degrees passed in a string to thef2c() function.f2c() then returns the Celsius number. This function approximates Perl'ss///e flag.

js
function f2c(x) {  function convert(str, p1, offset, s) {    return `${((p1 - 32) * 5) / 9}C`;  }  const s = String(x);  const test = /(-?\d+(?:\.\d*)?)F\b/g;  return s.replace(test, convert);}

Making a generic replacer

Suppose we want to create a replacer that appends the offset data to every matched string. Because the replacer function already receives theoffset parameter, it will be trivial if the regex is statically known.

js
"abcd".replace(/(bc)/, (match, p1, offset) => `${match} (${offset}) `);// "abc (1) d"

However, this replacer would be hard to generalize if we want it to work with any regex pattern. The replacer isvariadic — the number of arguments it receives depends on the number of capturing groups present. We can userest parameters, but it would also collectoffset,string, etc. into the array. The fact thatgroups may or may not be passed depending on the identity of the regex would also make it hard to generically know which argument corresponds to theoffset.

js
function addOffset(match, ...args) {  const offset = args.at(-2);  return `${match} (${offset}) `;}console.log("abcd".replace(/(bc)/, addOffset)); // "abc (1) d"console.log("abcd".replace(/(?<group>bc)/, addOffset)); // "abc (abcd) d"

TheaddOffset example above doesn't work when the regex contains a named group, because in this caseargs.at(-2) would be thestring instead of theoffset.

Instead, you need to extract the last few arguments based on type, becausegroups is an object whilestring is a string.

js
function addOffset(match, ...args) {  const hasNamedGroups = typeof args.at(-1) === "object";  const offset = hasNamedGroups ? args.at(-3) : args.at(-2);  return `${match} (${offset}) `;}console.log("abcd".replace(/(bc)/, addOffset)); // "abc (1) d"console.log("abcd".replace(/(?<group>bc)/, addOffset)); // "abc (1) d"

Specifications

Specification
ECMAScript® 2026 Language Specification
# sec-string.prototype.replace

Browser compatibility

See also

Help improve MDN

Learn how to contribute.

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp