JS: Regex Replace Function Args

By Xah Lee. Date: . Last updated: .

Some string replace functions take a function repFunc as replacement string. For example:

The function repFunc is called for each match. The function is feed the following args.

  1. matched string.
  2. 1st capture group. (named capture is also considered here)
  3. 2nd capture group.
  4. 3rd capture group.
  5. etc
  6. offset position (integer), of the matched substring in the target string.
  7. Whole target string.
  8. A data object of named capture groups. Key is the capture names, value is its capture string. (or undefined if none).

Show arguments received by function

// replaceAll. show arguments received by function

const xArgResult = [];

const ff = ((...xx) => {
  xArgResult.push(xx);
  return "";
});

const xinput = `
<img src="big_black_cat.jpg">
<img src="small_cat.jpg">
`;

const xre = /src="(?<xname>[\w]+)\.jpg"/g;

console.log(xinput.replaceAll(xre, ff));

console.log(xArgResult.length === 2);

console.log(xArgResult[0]);

/*
[
  'src="big_black_cat.jpg"',
  "big_black_cat",
  6,
  '\n<img src="big_black_cat.jpg">\n<img src="small_cat.jpg">\n',
  { xname: "big_black_cat" }
] */

console.log(xArgResult[1]);

/*
[
  'src="small_cat.jpg"',
  "small_cat",
  36,
  '\n<img src="big_black_cat.jpg">\n<img src="small_cat.jpg">\n',
  { xname: "small_cat" }
]
 */

JavaScript, Regular Expression

BUY ΣJS JavaScript in Depth