RegExp.prototype.exec()

The exec() method executes a search for a match in a specified string. Returns a result array, or null.

JavaScript RegExp objects are stateful when they have the global or sticky flags set (e.g. /foo/g or /foo/y). They store a lastIndex from the previous match. Using this internally, exec() can be used to iterate over multiple matches in a string of text (with capture groups), as opposed to getting just the matching strings with String.prototype.match().

A newer function has been proposed to simplify matching multiple parts of a string (with capture groups): String.prototype.matchAll().

If you are executing a match to find true or false, use RegExp.prototype.test() method instead.

If you are executing a match to find its index position in the string, use String.prototype.search() method instead.

Syntax

exec(str)

Parameters

str

The string against which to match the regular expression.

Return value

If the match succeeds, the exec() method returns an array (with extra properties index, input, and if the d flag is set, indices; see below) and updates the lastIndex property of the regular expression object. The returned array has the matched text as the first item, and then one item for each parenthetical capture group of the matched text.

If the match fails, the exec() method returns null, and sets lastIndex to 0.

Description

Consider the following example:

// Match "quick brown" followed by "jumps", ignoring characters in between
// Remember "brown" and "jumps"
// Ignore case
let re = /quick\s(brown).+?(jumps)/igd;
let result = re.exec('The Quick Brown Fox Jumps Over The Lazy Dog');

The following table shows the state of result after running this script:

Property/Index Description Example
[0] The full string of characters matched "Quick Brown Fox Jumps"
[1], ...[n]

The parenthesized substring matches, if any.

The number of possible parenthesized substrings is unlimited.

result[1] === "Brown"

result[2] === "Jumps"

index The 0-based index of the match in the string. 4
indices An array where each entry represents a substring match. Each substring match itself is an array where the first entry represents its start index and the second entry its end index.
The indices array additionally has a groups property which holds an object of all named capturing groups. The keys are the names of the capturing groups and each value is an array with the first item being the start entry and the second entry being the end index of the capturing group. If the regular expression doesn't contain any capturing groups, groups is undefined.

indices[0] === Array [ 4, 25 ]

indices[1] === Array [ 10, 15 ]

indices[2] === Array [ 20, 25 ]

indices.groups === undefined

indices.length === 3

input The original string that was matched against. The Quick Brown Fox Jumps Over The Lazy Dog

The following table shows the state of re after running this script:

Property/Index Description Example
lastIndex

The index at which to start the next match.

If g is absent, this will always be 0.

25
dotAll Indicates if the s flag was used to let . match newlines. false
hasIndices Indicates if the d flag was used to generate an indices property in the returned value containing start and end indices of the substring matches. true
ignoreCase Indicates if the i flag was used to ignore case. true
global Indicates if the g flag was used for a global match. true
multiline Indicates if the m flag was used to search across multiple lines. false
source The text of the pattern. quick\s(brown).+?(jumps)
sticky Indicates if the y flag was used to match only from the index indicated by the lastIndex property. false
unicode Indicates if the u flag was used to treat the pattern as a sequence of Unicode code points. false

Examples

Finding successive matches

If your regular expression uses the "g" flag, you can use the exec() method multiple times to find successive matches in the same string. When you do so, the search starts at the substring of str specified by the regular expression's lastIndex property (test() will also advance the lastIndex property). Note that the lastIndex property will not be reset when searching a different string, it will start its search at its existing lastIndex .

For example, assume you have this script:

let myRe = /ab*/g;
let str = 'abbcdefabh';
let myArray;
while ((myArray = myRe.exec(str)) !== null) {
  let msg = 'Found ' + myArray[0] + '. ';
  msg += 'Next match starts at ' + myRe.lastIndex;
  console.log(msg);
}

This script displays the following text:

Found abb. Next match starts at 3
Found ab. Next match starts at 9

Warning: Do not place the regular expression literal (or RegExp constructor) within the while condition!

It will create an infinite loop if there is a match, due to the lastIndex property being reset upon each iteration.

Also, be sure that the global flag ("g") is set, or it will also cause an infinite loop.

In addition, when matching zero-length characters (e.g. /^/gm), increase its lastIndex each time to avoid an infinite loop.

Using exec() with RegExp literals

You can also use exec() without creating a RegExp object explicitly:

let matches = /(hello \S+)/.exec('This is a hello world!');
console.log(matches[1]);

This will log a message containing 'hello world!'.

Specifications

Specification
ECMAScript Language Specification
# sec-regexp.prototype.exec

Browser compatibility

BCD tables only load in the browser

See also