developer.mozilla.org Open in urlscan Pro
2600:9000:225e:b600:2:eb5:8c00:93a1  Public Scan

Submitted URL: https://mdn.io/String/replace
Effective URL: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
Submission: On December 29 via api from US — Scanned from DE

Form analysis 1 forms found in the DOM

/en-US/search

<form action="/en-US/search" role="search" aria-haspopup="listbox" aria-owns="top-nav-search-menu" aria-expanded="false" class="search-form search-widget" id="top-nav-search-form"><label id="top-nav-search-label" for="top-nav-search-input"
    class="visually-hidden">Search MDN</label><input id="top-nav-search-input" aria-autocomplete="list" aria-controls="top-nav-search-menu" aria-labelledby="top-nav-search-label" autocomplete="off" type="search" class="search-input-field" name="q"
    placeholder="   " required="" value=""><button type="button" class="button action has-icon clear-search-button"><span class="button-wrap"><span class="icon icon-cancel "></span><span class="visually-hidden">Clear search
        input</span></span></button><button type="submit" class="button action has-icon search-button"><span class="button-wrap"><span class="icon icon-search "></span><span class="visually-hidden">Search</span></span></button>
  <div id="top-nav-search-menu" role="listbox" aria-labelledby="top-nav-search-label"></div>
</form>

Text Content

 * Skip to main content
 * Skip to search
 * Skip to select language

MDN Plus now available in your country! Support MDN and make it your own. Learn
more ✨


MDN Web DocsOpen main menu
 * ReferencesReferences
   * Overview / Web Technology
     
     Web technology reference for developers
   
   * HTML
     
     Structure of content on the web
   
   * CSS
     
     Code used to describe document style
   
   * JavaScript
     
     General-purpose scripting language
   
   * HTTP
     
     Protocol for transmitting web resources
   
   * Web APIs
     
     Interfaces for building web applications
   
   * Web Extensions
     
     Developing extensions for web browsers
   
   * Web Technology
     
     Web technology reference for developers
 * GuidesGuides
   * Overview / MDN Learning Area
     
     Learn web development
   
   * MDN Learning Area
     
     Learn web development
   
   * HTML
     
     Learn to structure web content with HTML
   
   * CSS
     
     Learn to style content using CSS
   
   * JavaScript
     
     Learn to run scripts in the browser
   
   * Accessibility
     
     Learn to make the web accessible to all
 * MDN PlusMDN Plus
   * Overview
     
     A customized MDN experience
   
   * 
     New feature
     Updates
     
     All browser compatibility updates at a glance
   
   * Documentation
     
     Learn how to use MDN Plus
   
   * FAQ
     
     Frequently asked questions about MDN Plus

Search MDNClear search inputSearch

Theme
 * Already a subscriber?
 * Get MDN Plus

 1. References
 2. JavaScript
 3. JavaScript
 4. Standard built-in objects
 5. String
 6. String.prototype.replace()

Article Actions
 * English (US)


IN THIS ARTICLE

 * Try it
 * Syntax
 * Description
 * Examples
 * Specifications
 * Browser compatibility
 * See also

RELATED TOPICS

 1.  Standard built-in objects
 2.  String
 3.  Properties
      1. String length

 4.  Methods
      1.  String.prototype[@@iterator]()
      2.  Deprecated String.prototype.anchor()
      3.  String.prototype.at()
      4.  Deprecated String.prototype.big()
      5.  Deprecated String.prototype.blink()
      6.  Deprecated String.prototype.bold()
      7.  String.prototype.charAt()
      8.  String.prototype.charCodeAt()
      9.  String.prototype.codePointAt()
      10. String.prototype.concat()
      11. String.prototype.endsWith()
      12. Deprecated String.prototype.fixed()
      13. Deprecated String.prototype.fontcolor()
      14. Deprecated String.prototype.fontsize()
      15. String.fromCharCode()
      16. String.fromCodePoint()
      17. String.prototype.includes()
      18. String.prototype.indexOf()
      19. Deprecated String.prototype.italics()
      20. String.prototype.lastIndexOf()
      21. Deprecated String.prototype.link()
      22. String.prototype.localeCompare()
      23. String.prototype.match()
      24. String.prototype.matchAll()
      25. String.prototype.normalize()
      26. String.prototype.padEnd()
      27. String.prototype.padStart()
      28. String.raw()
      29. String.prototype.repeat()
      30. String.prototype.replace()
      31. String.prototype.replaceAll()
      32. String.prototype.search()
      33. String.prototype.slice()
      34. Deprecated String.prototype.small()
      35. String.prototype.split()
      36. String.prototype.startsWith()
      37. Deprecated String.prototype.strike()
      38. Deprecated String.prototype.sub()
      39. Deprecated String.prototype.substr()
      40. String.prototype.substring()
      41. Deprecated String.prototype.sup()
      42. String.prototype.toLocaleLowerCase()
      43. String.prototype.toLocaleUpperCase()
      44. String.prototype.toLowerCase()
      45. String.prototype.toString()
      46. String.prototype.toUpperCase()
      47. String.prototype.trim()
      48. String.prototype.trimEnd()
      49. String.prototype.trimStart()
      50. String.prototype.valueOf()

 5.  Inheritance:
 6.  Function
 7.  Properties
      1. Non-standard Deprecated Function.prototype.arguments
      2. Non-standard Deprecated Function.prototype.caller
      3. Non-standard Function.prototype.displayName
      4. Function.prototype.length
      5. Function.prototype.name
      6. Function.prototype.prototype

 8.  Methods
      1. Function.prototype.apply()
      2. Function.prototype.bind()
      3. Function.prototype.call()
      4. Function.prototype.toString()

 9.  Object
 10. Properties
      1. Object.prototype.constructor
      2. Deprecated Object.prototype.__proto__

 11. Methods
      1.  Deprecated Object.prototype.__defineGetter__()
      2.  Deprecated Object.prototype.__defineSetter__()
      3.  Deprecated Object.prototype.__lookupGetter__()
      4.  Deprecated Object.prototype.__lookupSetter__()
      5.  Object.prototype.hasOwnProperty()
      6.  Object.prototype.isPrototypeOf()
      7.  Object.prototype.propertyIsEnumerable()
      8.  Object.setPrototypeOf()
      9.  Object.prototype.toLocaleString()
      10. Object.prototype.toString()
      11. Object.prototype.valueOf()


IN THIS ARTICLE

 * Try it
 * Syntax
 * Description
 * Examples
 * Specifications
 * Browser compatibility
 * See also


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.


TRY IT




SYNTAX

replace(pattern, replacement)


Copy to Clipboard


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"


Copy to Clipboard

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:

Pattern Inserts $$ 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. $n Inserts 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


Copy to Clipboard


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;
}


Copy to Clipboard

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 - #$*%


Copy to Clipboard

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 in replace() and
includes the ignore case flag.

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


Copy to Clipboard

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

Note: See the 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 the global and ignore case flags which
permits replace() to replace each occurrence of 'apples' in the string with
'oranges'.

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.


Copy to Clipboard

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 uses capturing groups and the $1 and $2 replacement patterns.

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


Copy to Clipboard

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.

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


Copy to Clipboard

Given styleHyphenFormat('borderTop'), this returns 'border-top'.

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

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


Copy to Clipboard

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 expression test checks for any number that ends with F. 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 the f2c() function. f2c() then returns
the Celsius number. This function approximates Perl's s///e flag.

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);
}


Copy to Clipboard


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 the offset
parameter, it will be trivial if the regex is statically known.

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


Copy to Clipboard

However, this replacer would be hard to generalize if we want it to work with
any regex pattern. The replacer is variadic — the number of arguments it
receives depends on the number of capturing groups present. We can use rest
parameters, but it would also collect offset, string, etc. into the array. The
fact that groups 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 the
offset.

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"


Copy to Clipboard

The addOffset example above doesn't work when the regex contains a named group,
because in this case args.at(-2) would be the string instead of the offset.

Instead, you need to extract the last few arguments based on type, because
groups is an object while string is a string.

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"


Copy to Clipboard


SPECIFICATIONS

SpecificationECMAScript Language Specification
# sec-string.prototype.replace


BROWSER COMPATIBILITY

Report problems with this compatibility data on GitHub

desktopmobileserver
Chrome

Edge

Firefox

Opera

Safari

Chrome Android

Firefox for Android

Opera Android

Safari on iOS

Samsung Internet

WebView Android

Deno

Node.js

replace
Full support
Chrome1
Toggle history
Full support
Edge12
Toggle history
Full support
Firefox1
Toggle history
Full support
Opera4
Toggle history
Full support
Safari1
Toggle history
Full support
Chrome Android18
Toggle history
Full support
Firefox for Android4
Toggle history
Full support
Opera Android10.1
Toggle history
Full support
Safari on iOS1
Toggle history
Full support
Samsung Internet1.0
Toggle history
Full support
WebView Android4.4
Toggle history
Full support
Deno1.0
Toggle history
Full support
Node.js0.10.0
Toggle history


LEGEND

Tip: you can click/tap on a cell for more information.

Full supportFull support
The compatibility table on this page is generated from structured data. If you'd
like to contribute to the data, please check out
https://github.com/mdn/browser-compat-data and send us a pull request.


SEE ALSO

 * Polyfill of String.prototype.replace in core-js with fixes and implementation
   of modern behavior like Symbol.replace support
 * String.prototype.replaceAll()
 * String.prototype.match()
 * RegExp.prototype.exec()
 * RegExp.prototype.test()
 * Symbol.replace
 * RegExp.prototype[@@replace]()


FOUND A PROBLEM WITH THIS PAGE?

 * Edit on GitHub
 * Source on GitHub
 * Report a problem with this content on GitHub
 * Want to fix the problem yourself? Learn how to contribute!

Last modified: Dec 13, 2022, by MDN contributors

MDN logo

Your blueprint for a better internet.

 * MDN on Twitter
 * MDN on GitHub


MDN

 * About
 * Hacks Blog
 * Careers


SUPPORT

 * Product help
 * Report an issue


OUR COMMUNITIES

 * MDN Community
 * MDN Forum
 * MDN Chat


DEVELOPERS

 * Web Technologies
 * Learn Web Development
 * MDN Plus

Mozilla logo
 * Website Privacy Notice
 * Cookies
 * Legal
 * Community Participation Guidelines

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998–2022 by individual mozilla.org contributors.
Content available under a Creative Commons license.