Skip to content

Commit 7fea476

Browse files
committed
Make XRegExp.exec set groups prop to undefined if there are no named captures (closes #320)
1 parent 5f18261 commit 7fea476

File tree

2 files changed

+15
-5
lines changed

2 files changed

+15
-5
lines changed

src/xregexp.js

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1078,7 +1078,7 @@ XRegExp.matchChain = (str, chain) => (function recurseChain(values, level) {
10781078

10791079
if (isNamedBackref && XRegExp.isInstalled('namespacing')) {
10801080
// `groups` has `null` as prototype, so using `in` instead of `hasOwnProperty`
1081-
if (!(item.backref in match.groups)) {
1081+
if (!(match.groups && item.backref in match.groups)) {
10821082
throw new ReferenceError(ERR_UNDEFINED_GROUP);
10831083
}
10841084
} else if (!match.hasOwnProperty(item.backref)) {
@@ -1408,13 +1408,16 @@ fixed.exec = function(str) {
14081408
}
14091409

14101410
// Attach named capture properties
1411-
let groupsObject = match;
14121411
if (XRegExp.isInstalled('namespacing')) {
1413-
// https://tc39.github.io/proposal-regexp-named-groups/#sec-regexpbuiltinexec
1414-
match.groups = Object.create(null);
1415-
groupsObject = match.groups;
1412+
match.groups = undefined;
14161413
}
14171414
if (this[REGEX_DATA] && this[REGEX_DATA].captureNames) {
1415+
let groupsObject = match;
1416+
if (XRegExp.isInstalled('namespacing')) {
1417+
// https://tc39.github.io/proposal-regexp-named-groups/#sec-regexpbuiltinexec
1418+
match.groups = Object.create(null);
1419+
groupsObject = match.groups;
1420+
}
14181421
// Skip index 0
14191422
for (let i = 1; i < match.length; ++i) {
14201423
const name = this[REGEX_DATA].captureNames[i - 1];

tests/spec/s-xregexp-methods.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -472,6 +472,13 @@ describe('XRegExp.exec()', function() {
472472
expect(match[1]).toBe('a');
473473
});
474474

475+
it('should set the groups property as undefined when there are no named captures if namespacing is installed', function() {
476+
var match = XRegExp.exec('a', XRegExp('(a)'));
477+
478+
expect(match.groups).toBeUndefined();
479+
expect(match.hasOwnProperty('groups')).toBe(true);
480+
});
481+
475482
it('should shadow array prototype properties with named capture properties if namespacing is not installed', function() {
476483
XRegExp.uninstall('namespacing');
477484
expect(XRegExp.exec('a', XRegExp('(?<concat>a)')).concat).toBe('a');

0 commit comments

Comments
 (0)