Movatterモバイル変換


[0]ホーム

URL:


  1. Web
  2. JavaScript
  3. Reference
  4. Standard built-in objects
  5. RegExp
  6. exec()

RegExp.prototype.exec()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since ⁨July 2015⁩.

Theexec() method ofRegExp instances executes a search with this regular expression for a match in a specified string and returns a result array, ornull.

Try it

const regex = /fo+/g;const str = "table football, foosball";let array;while ((array = regex.exec(str)) !== null) {  console.log(`Found ${array[0]}. Next starts at ${regex.lastIndex}.`);  // Expected output: "Found foo. Next starts at 9."  // Expected output: "Found foo. Next starts at 19."}

Syntax

js
exec(str)

Parameters

str

The string against which to match the regular expression. All values arecoerced to strings, so omitting it or passingundefined causesexec() to search for the string"undefined", which is rarely what you want.

Return value

If the match fails, theexec() method returnsnull, and sets the regex'slastIndex to0.

If the match succeeds, theexec() method returns an array and updates thelastIndex property of the regular expression object. The returned array has the matched text as the first item, and then one item for each capturing group of the matched text. The array also has the following additional properties:

index

The 0-based index of the match in the string.

input

The original string that was matched against.

groups

Anull-prototype object of named capturing groups, whose keys are the names, and values are the capturing groups, orundefined if no named capturing groups were defined. Seecapturing groups for more information.

indicesOptional

This property is only present when thed flag is set. It is an array where each entry represents the bounds of a substring match. The index of each element in this array corresponds to the index of the respective substring match in the array returned byexec(). In other words, the firstindices entry represents the entire match, the secondindices entry represents the first capturing group, etc. Each entry itself is a two-element array, where the first number represents the match's start index, and the second number, its end index.

Theindices array additionally has agroups property, which holds anull-prototype object of all named capturing groups. The keys are the names of the capturing groups, and each value is a two-element array, with the first number being the start index, and the second number being the end index of the capturing group. If the regular expression doesn't contain any named capturing groups,groups isundefined.

Description

JavaScriptRegExp objects arestateful when they have theglobal orsticky flags set (e.g.,/foo/g or/foo/y). They store alastIndex 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 withString.prototype.match().

When usingexec(), the global flag has no effect when the sticky flag is set — the match is always sticky.

exec() is the primitive method of regexps. Many other regexp methods callexec() internally — including those called by string methods, like[Symbol.replace](). Whileexec() itself is powerful (and is the most efficient), it often does not convey the intent most clearly.

  • If you only care whether the regex matches a string, but not what is actually being matched, useRegExp.prototype.test() instead.
  • If you are finding all occurrences of a global regex and you don't care about information like capturing groups, useString.prototype.match() instead. In addition,String.prototype.matchAll() helps to simplify matching multiple parts of a string (with capture groups) by allowing you to iterate over the matches.
  • If you are executing a match to find its index position in the string, use theString.prototype.search() method instead.

exec() is useful for complex operations that cannot be easily achieved via any of the methods above, often when you need to manually adjustlastIndex. (String.prototype.matchAll() copies the regex, so changinglastIndex while iterating overmatchAll does not affect the iteration.) For one such example, seerewindinglastIndex.

Examples

Using exec()

Consider the following example:

js
// Match "quick brown" followed by "jumps", ignoring characters in between// Remember "brown" and "jumps"// Ignore caseconst re = /quick\s(?<color>brown).+?(jumps)/dgi;const result = re.exec("The Quick Brown Fox Jumps Over The Lazy Dog");

The following table shows the state ofresult after running this script:

PropertyValue
[0]"Quick Brown Fox Jumps"
[1]"Brown"
[2]"Jumps"
index4
indices[[4, 25], [10, 15], [20, 25]]
groups: { color: [10, 15 ]}
input"The Quick Brown Fox Jumps Over The Lazy Dog"
groups{ color: "Brown" }

In addition,re.lastIndex will be set to25, due to this regex being global.

Finding successive matches

If your regular expression uses theg flag, you can use theexec() method multiple times to find successive matches in the same string. When you do so, the search starts at the substring ofstr specified by the regular expression'slastIndex property (test() will also advance thelastIndex property). Note that thelastIndex property will not be reset when searching a different string, it will start its search at its existinglastIndex.

For example, assume you have this script:

js
const myRe = /ab*/g;const 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 3Found ab. Next match starts at 9

Warning:There are many pitfalls that can lead to this becoming an infinite loop!

  • Donot place the regular expression literal (orRegExp constructor) within thewhile condition — it will recreate the regex for every iteration and resetlastIndex.
  • Be sure that theglobal (g) flag is set, orlastIndex will never be advanced.
  • If the regex may match zero-length characters (e.g.,/^/gm), increase itslastIndex manually each time to avoid being stuck in the same place.

You can usually replace this kind of code withString.prototype.matchAll() to make it less error-prone.

Using exec() with RegExp literals

You can also useexec() without creating aRegExp objectexplicitly:

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

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

Specifications

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

Browser compatibility

See also

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp