$1 must be inside the string:

"string".replace(/st(ring)/, "gold $1") 
// output -> "gold ring"

with a function:

"string".replace(/st(ring)/, function (match, capture) { 
    return "gold " + capture + "|" + match;
}); 
// output -> "gold ring|string"
Answer from Joe on Stack Overflow
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › String › replace
String.prototype.replace() - JavaScript - MDN Web Docs
The whole string being examined. ... 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 - #$*%
Discussions

JavaScript String Replace with regular expression and function as arguments - Stack Overflow
He goes on to say When the regular ... the function gets passed three arguments (as above). When there are multiple capture groups, each matched string is passed in as an argument, with the last two positions being the position and originalText... Then we come to Doug Crockfords, JavaScript: The Good Parts. (P90): He stipulates the syntax again as string(searcValue,replaceValue) searchValue ... More on stackoverflow.com
🌐 stackoverflow.com
November 10, 2011
JavaScript replace method takes functions as arguments - JavaScript - SitePoint Forums | Web Development & Design Community
Hi, I am pretty new to javascript. I encountered some code in “Javascript the good part” from Douglas Crockford. There is a way to passing callback function as second argument to string.replace() method. var entity … More on sitepoint.com
🌐 sitepoint.com
0
February 13, 2010
regex - Javascript: how to pass found string.replace value to function? - Stack Overflow
Creates the function and immediately evaluates it, passing $1 as an argument. The str.replace method already receives a string as its second argument, not a function. More on stackoverflow.com
🌐 stackoverflow.com
How does the replace function of a string work in JavaScript when passing a function as its second argument - Stack Overflow
Communities for your favorite technologies. Explore all Collectives · Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work More on stackoverflow.com
🌐 stackoverflow.com
🌐
W3Schools
w3schools.com › jsref › jsref_replace.asp
JavaScript String replace() Method
string.replace(searchValue, newValue) A global, case-insensitive replacement: let text = "Mr Blue has a blue house and a blue car"; let result = text.replace(/blue/gi, "red"); Try it Yourself » · A function to return the replacement text: let text = "Mr Blue has a blue house and a blue car"; let result = text.replace(/blue|house|car/gi, function (x) { return x.toUpperCase(); }); Try it Yourself » · JavaScript Strings ·
Top answer
1 of 2
8

Zakas is correct, the penultimate and final arguments are pos and originalText. From the ECMA-262 3rd and 5th editions (section 15.5.4.11):

If replaceValue is a function, then for each matched substring, call the function with the following m + 3 arguments. Argument 1 is the substring that matched. If searchValue is a regular expression, the next m arguments are all of the captures in the MatchResult (see 15.10.2.1). Argument m + 2 is the offset within string where the match occurred, and argument m + 3 is string.

Note that String.prototype.replace was new in ECMA-262 3rd edition. MSDN documentation for JScript and MDC documentation for JavaScript both conform to this specification.

  • replace Method (Windows Scripting - JScript)
  • replace - MDC
2 of 2
4

The ECMAScript spec has:

String.prototype.replace (searchValue, replaceValue)

If searchValue is a regular expression (an object whose [[Class]] property is "RegExp"), do the following: If searchValue. global is false, then search string for the first match of the regular expression searchValue. If searchValue.global is true, then search string for all matches of the regular expression searchValue. Do the search in the same manner as in String.prototype.match, including the update of searchValue. lastIndex. Let m be the number of left capturing parentheses in searchValue (NCapturingParens as specified in 15.10.2.1).

If searchValue is not a regular expression, let searchString be ToString(searchValue) and search string for the first occurrence of searchString. Let m be 0.

If replaceValue is a function, then for each matched substring, call the function with the following m + 3 arguments. Argument 1 is the substring that matched. If searchValue is a regular expression, the next m arguments are all of the captures in the MatchResult (see 15.10.2.1). Argument m + 2 is the offset within string where the match occurred, and argument m + 3 is string. The result is a string value derived from the original input by replacing each matched substring with the corresponding return value of the function call, converted to a string if need be.

It's a bit confusing but I think Zakas is right.

🌐
Tutorial Gateway
tutorialgateway.org › javascript-replace
JavaScript replace String Function
June 11, 2026 - Return Value: The JavaScript replace() function does not modify the original string. Instead, it returns a new string with the replacements. For advanced pattern matching, use the regular expression as the replace() function’s first argument.
🌐
TutorialsPoint
tutorialspoint.com › javascript › string_replace.htm
JavaScript String replace() Method
In the following program, we specify a string "$2" as the replacement argument to the replace() method. The regular expression does not have a second group, so it replaces and returns "$2oo". <html> <head> <title>JavaScript String replace() Method</title> </head> <body> <script> const str = "foo"; let replacement = "$2"; document.write("Original string: ", str); document.write("<br>Replacement: ", replacement); document.write("<br>New String after replacement: ", str.replace(/(f)/, replacement)); </script> </body> </html>
🌐
SitePoint
sitepoint.com › javascript
JavaScript replace method takes functions as arguments - JavaScript - SitePoint Forums | Web Development & Design Community
February 13, 2010 - There is a way to passing callback function as second argument to string.replace() method. var entity = { quot: '"', lt: ' ' }; var finalStr = ' '.replace(/&([^&;]+);/g, function (a, b) { var r = entity[b]; return typeof r === 'string' ? r : a; } ...
Find elsewhere
🌐
The Code Barbarian
thecodebarbarian.com › string-replace-in-javascript.html
String Replace in JavaScript | www.thecodebarbarian.com
March 21, 2019 - There are several special character sequences that you can use in the 2nd argument to replace(). For example, suppose you want to wrap all numbers in a string in parentheses. JavaScript replaces $& in the replacement string with the matched string, so you can wrap all numbers in parentheses as shown below.
🌐
JavaScript Tutorial
javascripttutorial.net › home › javascript string methods › string.prototype.replace()
JavaScript String replace() Method
November 4, 2024 - In this tutorial, you'll how to use JavaScript String replace() function to replace a substring in a string with a new one.
🌐
CodeSweetly
codesweetly.com › javascript-string-replace-method
replace() JavaScript String Method – How to Replace Text Strings | CodeSweetly
You can use a function as replace()’s newValue argument. Let’s discuss the above points. Section titled “How to Use Special Replacement Patterns when replace()’s newValue Argument Is a String” · JavaScript has some special patterns that you can use if replace()’s second argument is a string.
🌐
Flavio Copes
flaviocopes.com › home › javascript › the string replace() method
The String replace() method
February 11, 2019 - Since $ is special in the replacement string, a replacement value you don’t control can surprise you. If it contains $& or $$, those get expanded instead of inserted literally. To insert a value literally, use a function as the replacement. Whatever the function returns is used as-is, with no $ processing: const nickname = 'the $& master' 'Hello NAME'.replace('NAME', () => nickname) //'Hello the $& master' ... Enjoyed this? Grab my JavaScript Handbook for free.
🌐
Career Karma
careerkarma.com › blog › javascript › javascript replace(): a step-by-step guide
JavaScript Replace(): A Step-By-Step Guide | Career Karma
December 1, 2023 - To replace text in a JavaScript string the replace() function is used. The replace() function takes two arguments, the substring to be replaced and the new string that will take its place.
🌐
Tabnine
tabnine.com › home › how to use the string.prototype replace method in javascript
How to Use the String.prototype replace Method in JavaScript - Tabnine
July 25, 2024 - The “g” is again used to indicate a global search; without it, only the first character of the original string will be replaced. The newValue parameter received a function which does the following: For every character in the string, let i is declared and assigned the value of the character’s Unicode code value + 5 (note – this is a numeric value). The character’s Unicode value is retrieved using the charCodeAt() method. The function returns a character using the calculated value with the fromCharCode() method, which converts an integer Unicode value (or any other number of significance) into its corresponding character.
🌐
Bennadel
bennadel.com › blog › 55-using-methods-in-javascript-replace-method.htm
Using Methods in Javascript Replace Method
April 18, 2020 - I never knew you could do this, but you can use a nameless method as the "replace" argument to the Javascript String replace() method call. See in the example below that I take a string and turn each non-vowel characer into a randomly upper ...
🌐
EDUCBA
educba.com › home › software development › software development tutorials › javascript tutorial › replace function in javascript
Replace Function in JavaScript | How replace function works in javascript?
July 28, 2023 - The JavaScript replace() function replaces the string or substring, bypassing the string as a value or regular expression. We can also call functions from inside to perform more changes on the string, like uppercase, lowercase, etc.
Address: Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › String › replaceAll
String.prototype.replaceAll() - JavaScript - MDN Web Docs
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 replaceAll().
🌐
Stack Overflow
stackoverflow.com › questions › 62956329 › how-does-the-replace-function-of-a-string-work-in-javascript-when-passing-a-func
How does the replace function of a string work in JavaScript when passing a function as its second argument - Stack Overflow
camelize = function camelize(str) { return str.replace(/\W+(.)/g, function(match, chr) { return chr.toUpperCase(); }); } What is in the argument match and char, which is passed to replace function as second parameter.
🌐
HTML Goodies
htmlgoodies.com › home › javascript
JavaScript's Amazingly Versatile Replace Function | HTML Goodies
May 2, 2022 - Although it only takes two arguments, this simple signature belies replace’s amazing versatility, as these can be of different types, depending on how exacting you need it to be. This JavaScript programming tutorial will provide an overview of JS’s Swiss army knife of functions and examples of its many uses. Technically speaking, replace() is a public method of the String object.
🌐
Scaler
scaler.com › home › topics › replace() in javascript
String replace() in JavaScript - Scaler Topics
March 1, 2024 - The first parameter of replace() in JavaScript can be a string or a pattern to be matched within the given string, whereas the second parameter can be a new string or a function that will be invoked to create a new string.