• Skip to main content
  • Skip to search
  • Skip to select language
HTML

Structure of content on the web

  • Web APIs

    Interfaces for building web applications

  • Learn
    • CSS

      Learn to style content using CSS

    • Overview

      A customized MDN experience

    • FAQ

      Frequently asked questions about MDN Plus

  • HTTP Observatory

    Scan a website for free

  • JavaScript
  • exec()
      • Deutsch
      • Español
      • Français
      • 日本語
      • Português (do Brasil)
      • Русский
      • 中文 (简体)

    In this article

    • Try it
    • Syntax
    • Description
    • Examples
    • Specifications
    • Browser compatibility
    • See also
    1. escape()
  • Static properties
    1. $1, …, $9 Deprecated
    2. input ($_) Deprecated
    3. lastMatch ($&) Deprecated
    4. lastParen ($+) Deprecated
    5. leftContext ($`) Deprecated
    6. rightContext ($') Deprecated
    7. compile() Deprecated
    8. [Symbol.match]()
    9. [Symbol.split]()
  • Instance properties
    1. global
    2. source
    3. Object/Function
    4. Static methods
      1. toString()
      2. displayName Non-standard
      3. arguments Non-standard Deprecated
      4. caller Non-standard Deprecated
    5. Instance methods
      1. __defineGetter__() Deprecated
      2. __defineSetter__() Deprecated
      3. __lookupGetter__() Deprecated
      4. __lookupSetter__() Deprecated
      5. toLocaleString()
      6. __proto__ Deprecated
      7. null.

  • Try it

    const regex1 = /fo+/g;
    const str1 = "table football, foosball";
    let array1;
    
    while ((array1 = regex1.exec(str1)) !== null) {
      console.log(`Found ${array1[0]}. Next starts at ${regex1.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 are coerced to strings, so omitting it or passing undefined causes exec() to search for the string "undefined", which is rarely what you want.

    Return value

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

    If the match succeeds, the exec() method returns an array 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 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

    A capturing groups for more information.

    indices Optional

    This property is only present when the d 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 by exec(). In other words, the first indices entry represents the entire match, the second indices 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.

    The indices array additionally has a groups property, which holds a null-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 is undefined.

    Description

    JavaScript 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().

    When using exec(), 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 call exec() internally — including those called by string methods, like [Symbol.replace](). While exec() 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, use RegExp.prototype.test() instead.
    • If you are finding all occurrences of a global regex and you don't care about information like capturing groups, use 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 the String.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 adjust rewinding lastIndex.

    Examples

    Using exec()

    Consider the following example:

    js
    / Match "quick brown" followed by "jumps", ignoring characters in between
    / Remember "brown" and "jumps"
    / Ignore case
    const 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 of result after running this script:

    Property Value
    [0] "Quick Brown Fox Jumps"
    [1] "Brown"
    [2] "Jumps"
    index 4
    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 to 25, due to this regex being global.

    Finding successive matches

    If your regular expression uses the lastIndex property). Note that the lastIndex.

    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 3
    Found ab. Next match starts at 9
    

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

    • Do not place the regular expression literal (or lastIndex.
    • Be sure that the global (g) flag is set, or lastIndex will never be advanced.
    • If the regex may match zero-length characters (e.g., /^/gm), increase its lastIndex manually each time to avoid being stuck in the same place.

    You can usually replace this kind of code with RegExp object explicitly:

    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

    • Regular expressions guide
    • RegExp

    Help improve MDN

    RegExp object represents a regular expression, a notation for matching text patterns.","name":"Regular expressions"}},"browserCompat":["javascript.builtins.RegExp.exec"],"pageType":"javascript-instance-method"}}

    Follow Lee on X/Twitter - Father, Husband, Serial builder creating AI, crypto, games & web tools. We are friends :) AI Will Come To Life!

    Check out: eBank.nz (Art Generator) | Netwrck.com (AI Tools) | Text-Generator.io (AI API) | BitBank.nz (Crypto AI) | ReadingTime (Kids Reading) | RewordGame | BigMultiplayerChess | WebFiddle | How.nz | Helix AI Assistant