JavaScript Reference ยท RegExp
RegExp.prototype.exec()
Reference for JavaScript RegExp exec(): get the matched text, capture groups, index and named groups, and loop over matches safely with the g flag.
The exec() method runs a regular expression against a string and returns detailed information about one match, or null when there is no match. The result looks like an array: element 0 is the matched text and the following elements are the capture groups. It also carries index, input and groups properties.
Call exec() when you need more than yes or no. With the g or y flag it keeps track of its position in lastIndex, so calling it again continues with the next match.
const match = /(\d{4})-(\d{2})/.exec("Due 2026-03"); match[0]; // "2026-03" match[1]; // "2026" match.index; // 4
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
regex.exec(string)
| Name | Description |
|---|---|
string |
The text to search. Other values are converted to strings. |
Return value: null if nothing matched. Otherwise an array-like object with:
[0]: the full match, and[1],[2], ... : the capture groups (undefinedfor a group that did not participate).index: the position where the match starts.input: the original string.groups: an object with named groups, orundefinedif the pattern has none.indices: start and end pairs for the match and each group, only when thedflag is set.
Exceptions: a TypeError if called on something that is not a regular expression.
Usage notes
- Stateful with
gandy. Each call starts atlastIndex. After the last match the call returnsnulland resetslastIndexto0. - Never loop on a regex literal.
while (/o/g.exec(text))creates a new regex on every check and never ends. Store the regex in a variable first. - An empty match does not advance
lastIndexby itself. A pattern like/a*/gin a hand-written loop can loop forever; advancelastIndexmanually, or usematchAll(). - Prefer
matchAll()for iterating over every match. It returns an iterator, needs no manuallastIndexhandling, and does not mutate the regex you pass in. - Without
g,exec()always returns the first match, so the same call gives the same result every time. - Groups: when a group is inside a repeated part, the result shows its last repetition.
groupshas a null prototype, so it has notoString()or other inherited methods; spread it with{ ...match.groups }if you want a normal object.- Use
test()when you only need a boolean.
Browser support
exec() works everywhere. Named groups and the d flag (match indices) are newer; check a compatibility table if you support older browsers.