-
-
Notifications
You must be signed in to change notification settings - Fork 275
Closed
Description
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
groupsobject on result arrays.- For
String.prototype.replacereplacement functions (where named backreferences are added as properties of the first String argument), maybe leave things as they are (nogroupsobject). If https://github.com/tc39/proposal-regexp-named-groups moves beyond the proposal stage, then XRegExp should follow wherever ECMAScript is headed.
- For
- When enabled,
lengthand__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.
dploeger