Skip to content

Move named backreferences to a groups object #175

@slevithan

Description

@slevithan

Right now, looping over named backreferences after executing a regex with named groups is unnecessarily difficult, since XRegExp augments match arrays with the named backreferences as direct properties. It would be nice to give access to a clean object with named groups.

Proposal:

  • Add a new option "namespacing" to XRegExp.install/uninstall/isInstalled.
  • This option would be off by default in the initial version when it is introduced. In the subsequent major version (to enable a breaking change), the "namespacing" option will be on by default, and the ability to turn it off might be removed.
  • When enabled, named backreferences are no longer added as direct properties of match arrays. Rather, they are added to a groups object on result arrays.
    • For String.prototype.replace replacement functions (where named backreferences are added as properties of the first String argument), maybe leave things as they are (no groups object). If https://github.com/tc39/proposal-regexp-named-groups moves beyond the proposal stage, then XRegExp should follow wherever ECMAScript is headed.
  • When enabled, length and __proto__ should no longer be reserved words for named captures. Using __proto__ as a capture name would still lead to undesired results, so don’t do that.

As a workaround for now, here's how you can get a clean object with named groups:

function groups(regex, match) {
    var o = {};
    var x = regex.xregexp;
    (x && x.captureNames || []).forEach(function(name) {
        if (name) {
            o[name] = match[name];
        }
    });
    return o;
}

// Use it
var regex = XRegExp('(?s)(?<char>.)');
var match = XRegExp.exec('test', regex);
groups(regex, match);
// -> {char: 't'}

Moved here from #45 (comment) since that was a long thread.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions