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 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
- JS: RegExp Tutorial
- JS: Regex Functions
- JS: RegExp Syntax
- JS: RegExp Flag
- JS: Regex Replace String Dollar Sign
- JS: Regex Replace Function Args
- JS: RegExp Object
- JS: RegExp Constructor
- JS: RegExp.prototype
- JS: String.prototype.search
- JS: String.prototype.match
- JS: String.prototype.matchAll
- JS: String.prototype.replace
- JS: String.prototype.replaceAll
- JS: RegExp.prototype.test
- JS: RegExp.prototype.exec