diff --git a/spec/regex-tag.spec.js b/spec/regex-tag.spec.js index 669ac69..9a1d363 100644 --- a/spec/regex-tag.spec.js +++ b/spec/regex-tag.spec.js @@ -157,6 +157,13 @@ describe('regex', () => { expect([...'ab'.matchAll(regex({flags: 'g', subclass: false})`(?>(?.))(?.)`)][0][2]).not.toBe('b'); expect('ab'.split(regex({subclass: false})`(?>(?.))(?.)`)).not.toEqual(['', 'a', 'b', '']); }); + + it('should adjust indices with flag d for emulation groups', () => { + expect(regex({flags: 'd', subclass: true})`(?>.)`.exec('a').indices).toHaveSize(1); + + // Documenting behavior when the option is not used + expect(regex({flags: 'd', subclass: false})`(?>.)`.exec('a').indices).toHaveSize(2); + }); }); }); }); diff --git a/src/regex.js b/src/regex.js index c096f74..1f1ae88 100644 --- a/src/regex.js +++ b/src/regex.js @@ -243,12 +243,20 @@ class WrappedRegExp extends RegExp { if (!match || !this.#captureMap) { return match; } - const copy = [...match]; + const matchCopy = [...match]; // Empty all but the first value of the array while preserving its other properties match.length = 1; - for (let i = 1; i < copy.length; i++) { + let indicesCopy; + if (this.hasIndices) { + indicesCopy = [...match.indices]; + match.indices.length = 1; + } + for (let i = 1; i < matchCopy.length; i++) { if (this.#captureMap[i]) { - match.push(copy[i]); + match.push(matchCopy[i]); + if (this.hasIndices) { + match.indices.push(indicesCopy[i]); + } } } return match;