$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 - If we pass a function as the replace() ... as the replacement text (new). ... The replace() function accepts the search term and replacement term as the two parameter values. It searches the entire string for the old text....
🌐
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 - Using the /str/ syntax can be inconvenient if the string you want to replace has slashes or special characters. In that case, you can use JavaScript's RegExp constructor. // Pass 'g' as the 2nd argument to set the global flag const re = new RegExp('/home/user', 'g'); '/home/user/path/to/file.txt'.replace(re, '~'); // '~/path/to/file.txt' re.global; // true
🌐
Scaler
scaler.com › home › topics › replace() in javascript
String replace() in JavaScript - Scaler Topics
March 1, 2024 - The replace() in JavaScript is an inbuilt function that allows you to replace a part of the given string with another string/regular expression.
🌐
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.
🌐
Flavio Copes
flaviocopes.com › home › javascript › the string replace() method
The String replace() method
February 11, 2019 - This also works for regular strings, not just regexes: 'JavaScript'.replace('Java', (match, index, originalString) => { console.log(match, index, originalString) return 'Test' }) //TestScript · In case your regex has capturing groups, those values will be passed as arguments right after the match parameter:
🌐
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 - The JavaScript replace() method searches a string for a pattern or regular expression. If that pattern is found in the string, it is replaced with a specified value. replace() returns a new string. The original string is not changed.
🌐
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
🌐
CodeSweetly
codesweetly.com › javascript-string-replace-method
replace() JavaScript String Method – How to Replace Text Strings | CodeSweetly
replace() returns a new version of its calling string after replacing some specified patterns with a given replacement.
🌐
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.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › String › replaceAll
String.prototype.replaceAll() - JavaScript - MDN Web Docs
While you can mitigate this case using RegExp.escape() to make the regular expression string into a literal pattern, it is simpler to pass the string to replaceAll() directly, without converting it to a regex. ... function unsafeRedactName(text, name) { return text.replace(new RegExp(name, "g"), "[REDACTED]"); } function semiSafeRedactName(text, name) { return text.replaceAll(name, "[REDACTED]"); } function superSafeRedactName(text, name) { // only match at word boundaries return text.replaceAll( new RegExp(`\\b${RegExp.escape(name)}\\b`, "g"), "[REDACTED]", ); } let report = "A hacker called
🌐
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 ...