Skip to content
Tutorials Center
My learning

Topics

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.

JavaScript
const match = /(\d{4})-(\d{2})/.exec("Due 2026-03");
match[0]; // "2026-03"
match[1]; // "2026"
match.index; // 4

Try it

JS Reading a match

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Looping with the g flag and d indices

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
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 (undefined for a group that did not participate).
  • index: the position where the match starts.
  • input: the original string.
  • groups: an object with named groups, or undefined if the pattern has none.
  • indices: start and end pairs for the match and each group, only when the d flag is set.

Exceptions: a TypeError if called on something that is not a regular expression.

Usage notes

  • Stateful with g and y. Each call starts at lastIndex. After the last match the call returns null and resets lastIndex to 0.
  • 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 lastIndex by itself. A pattern like /a*/g in a hand-written loop can loop forever; advance lastIndex manually, or use matchAll().
  • Prefer matchAll() for iterating over every match. It returns an iterator, needs no manual lastIndex handling, 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.
  • groups has a null prototype, so it has no toString() 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.