CKTIS / JavaScript
RegExp.prototype.exec — matching and capture groups
RegExp.prototype.exec searches for a match and returns an array containing the matched text and captures, or null. The g and y flags make successive calls use and update lastIndex.
Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support
Syntax
regexp.exec(string)regexp.exec(string) performs regular-expression matching. The argument is converted to a string; the built-in method requires an actual RegExp instance as this. Its result is an array or null, not a boolean. Check the result before reading its properties.
match[0] contains the full match, and match[1] onward contain capturing groups; a group that did not participate produces undefined. match.index is the starting position in UTF-16 code units, and match.input is the searched string. match.groups contains named groups, or undefined if the pattern has none. The d flag additionally exposes match.indices with start/end pairs; the end is exclusive.
Without g or y, searching starts at position 0 and leaves lastIndex unchanged. If either flag is set, the search uses the result of applying ToLength to lastIndex as its starting offset (for example, 1.9 becomes 1). With g but not y, the search may try later positions after a failed attempt; with y, it does not. In Unicode-aware mode (u or v), if the coerced lastIndex points to the trailing surrogate of a UTF-16 surrogate pair, a match can start at the leading surrogate of that pair. Thus, even with y, the reported match.index need not equal the coerced lastIndex. Success sets lastIndex to the end of the match, while failure resets it to zero. Before reusing such an object for an independent search, set lastIndex = 0.
Keep the same RegExp object inside a loop. Warning: an empty match does not automatically advance lastIndex; without explicit advancement or a break, the loop may never terminate. The example uses a pattern that always matches at least one character and demonstrates the reset after the final failure.
Examples
const regexp = /([a-z]+)=(\d+)/g;
const text = "x=12 y=7";
let match;
while ((match = regexp.exec(text)) !== null) {
console.log(JSON.stringify([match[0], match[1], match[2], match.index, regexp.lastIndex]));
}
console.log(regexp.lastIndex);Result
["x=12","x","12",0,4] ["y=7","y","7",5,8] 0
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.