javascriptregexcapture-group

Named capture groups in the function version of `replace()`


I notice you can actually get passed your named capture groups in the replace callback:

'Yoda said "fear leads to anger."'.replace(
    /(?<pre>\b\w+\b)(?<betwixt> leads to )(?<post>\b\w+\b)/,
    (...args) => {
        let [{pre, betwixt, post}] = args.slice(-1);
        let ani = {fear:'anger',anger:'hate',hate:'suffering'};
        return `${ani[pre]}${betwixt}${ani[post]}`;
    }
)

Results in Yoda said "anger leads to hate.". At least in chrome.

My question is where is this defined? It definitely doesn't seem standardised.
It appears to be always the last parameter, after string.

I'd like to know if it's an upcoming standard, or something whacky the chrome devs have temporarily that I accidentally discovered, and it'll disappear :(


Solution

  • The linked MDN documentation from the question now describes this new parameter, and explicitly defines exactly what was observed:

    The function has the following signature:

    function replacer(match, p1, p2, /* …, */ pN, offset, string, groups) {
      return replacement;
    }
    

    ...

    groups

    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.


    What's interesting is the browser compatibility section at the bottom makes no effort to differentiate between this new feature (which didn't work in Firefox at the time), simply saying "Firefox 1 full support" even though other mdn articles are usually very good at exhaustively listing browsers and at what version they each supported all the different sub-features separately.