JS: Regex Replace Function Args
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.
- matched string.
- 1st capture group. (named capture is also considered here)
- 2nd capture group.
- 3rd capture group.
- etc
- offset position (integer), of the matched substring in the target string.
- Whole target string.
- 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 print_args = (...x) => { console.log(x); return ""; }; console.log( "a5597-2452 b7623-4463 c9219-7228" .replaceAll( /\d+-(?<xname>\d+)/g, print_args, ), ); /* output [ "5597-2452", "2452", 1, "a5597-2452 b7623-4463 c9219-7228", [Object: null prototype] { xname: "2452" } ] [ "7623-4463", "4463", 12, "a5597-2452 b7623-4463 c9219-7228", [Object: null prototype] { xname: "4463" } ] [ "9219-7228", "7228", 23, "a5597-2452 b7623-4463 c9219-7228", [Object: null prototype] { xname: "7228" } ] a b c */