JavaScript RegExp exec() Method

Beginner
⏱️ 9 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Match & capture

What You’ll Learn

exec() runs a regular expression against a string and returns rich match details—full text, capture groups, and position—or null when nothing matches. This guide covers syntax, looping with the global flag, and how exec() compares to test() and match().

01

Syntax

regex.exec(str)

02

Match

result[0]

03

Groups

result[1]…

04

No match

null

05

Global loop

while + g

06

Position

result.index

Introduction

Regular expressions describe patterns in text. Once you have a RegExp object, you need a way to run it against a string and read what matched. RegExp.prototype.exec() is the core method for that job.

Unlike test(), which only answers yes or no, exec() returns an array-like object with the matched substring, any capture groups, the start index, and the original input string. That makes it ideal for parsers, validators, and tokenizers.

Understanding the exec() Method

regex.exec(string) searches string for the pattern held by regex:

  • Success — returns an array-like object. [0] is the full match; [1], [2], … are captured groups in order.
  • Failure — returns null. Always guard before reading properties.
  • index — zero-based position where the match starts in the string.
  • input — the string that was searched (same as the argument you passed).
  • Global regex — with the g flag, each call continues from regex.lastIndex until no match remains.
💡
Beginner Tip

Think of result[0] as “what matched entirely” and result[1] as “what the first pair of parentheses captured.” Parentheses create numbered groups left to right.

📝 Syntax

JavaScript
regex.exec(string)

Parameters

  • regex — the RegExp object with your pattern and flags.
  • string — the text to search (converted to string if needed).

Return value

  • Array-like match result with index and input properties, or
  • null when the pattern does not match.

Result shape (when matched)

JavaScript
result[0]     // full match
result[1]     // first capture group (if any)
result.index  // start position
result.input  // original string

⚡ Quick Reference

GoalCode
Run a match/pat/.exec(text)
Full match textresult[0]
First capture groupresult[1]
Match start indexresult.index
No matchnull
All matches (global)while ((m = /pat/g.exec(s)) !== null)

📋 exec() vs test() vs match()

Pick the method that returns the detail level you need.

exec()
groups + index

Detailed match

test()
true / false

Quick check

match()
string method

Convenient API

Global loop
exec + g flag

Iterate matches

Examples Gallery

Open DevTools Console (F12) or use Try-it links. Every example shows how to read the exec result safely.

📚 Getting Started

Run exec() and read the first match.

Example 1 — Basic Pattern Match

Find the word world inside a sentence.

JavaScript
const regex = /world/;
const result = regex.exec("hello world");

console.log(result[0]);      // "world"
console.log(result.index);   // 6
Try It Yourself

How It Works

result[0] holds the matched substring. result.index tells you it starts at character position 6 (zero-based), right after "hello ".

📈 Practical Patterns

Groups, null checks, and iteration.

Example 2 — Read Capture Groups

Extract the username and domain from an email-like pattern.

JavaScript
const regex = /(\w+)@(\w+\.\w+)/;
const result = regex.exec("Contact: ada@example.com today");

console.log(result[0]);  // "ada@example.com"
console.log(result[1]);  // "ada"
console.log(result[2]);  // "example.com"
Try It Yourself

How It Works

Each pair of parentheses creates a numbered group. The first (\w+) captures the local part; the second captures the domain. Parentheses do not appear in the output—only what they matched.

Example 3 — Handle No Match (null)

Always check the return value before reading indexes.

JavaScript
const regex = /zzz/;
const result = regex.exec("hello world");

if (result === null) {
  console.log("No match found.");
} else {
  console.log(result[0]);
}
Try It Yourself

How It Works

When the pattern cannot match, exec() returns null—not an empty array. Reading result[0] without a check throws a TypeError.

Example 4 — Loop All Matches with the g Flag

Collect every number in a string using a while loop.

JavaScript
const regex = /\d+/g;
const text = "a1 b22 c333";
const matches = [];

let match;
while ((match = regex.exec(text)) !== null) {
  matches.push(match[0] + " at index " + match.index);
}

console.log(matches.join("\n"));
Try It Yourself

How It Works

With the global flag, each exec() call resumes from regex.lastIndex. The loop stops when exec() returns null. Without g, repeated calls would keep returning the same first match.

Example 5 — Inspect index and input

Read metadata on the result object alongside capture groups.

JavaScript
const regex = /(JS)(\d+)/;
const text = "Learn JS2026 today";
const result = regex.exec(text);

console.log("full:", result[0]);    // JS2026
console.log("g1:", result[1]);      // JS
console.log("g2:", result[2]);      // 2026
console.log("index:", result.index); // 6
console.log("input:", result.input); // Learn JS2026 today
Try It Yourself

How It Works

Besides numbered slots, the result carries index (where the match begins) and input (the full searched string). These fields help when you slice or replace surrounding text.

🚀 Common Use Cases

  • Extract tokens — pull dates, IDs, or hashtags with capture groups.
  • Validate formats — confirm structure and read parts (area code, extension).
  • Parse logs — loop with g to scan repeated entries in one line.
  • Build lexers — repeated exec calls power hand-written parsers.
  • Replace with context — use index to splice matched regions.
  • Debug regexes — log full result objects while tuning patterns.

🧠 How exec() Searches a String

1

Start position

Non-global regexes search from the beginning. Global regexes start at lastIndex.

lastIndex
2

Run pattern

The engine tries to match the RegExp pattern against the substring.

Pattern engine
3

Build result

On success, fill [0], groups, index, and input. On failure, return null.

Array-like
4

Advance (global)

With g, update lastIndex for the next loop iteration.

📝 Notes

  • Always check for null before using result[0] or groups.
  • Without the g flag, looping exec() repeats the first match.
  • Global regexes update lastIndex—reset it with regex.lastIndex = 0 when re-scanning.
  • Capture groups are numbered from 1; 0 is always the full match.
  • exec() does not modify the input string.
  • For a simple boolean check, test() is shorter than exec().

Browser & Runtime Support

RegExp.prototype.exec() has been part of JavaScript since ES3 and works identically in every modern runtime.

Baseline · ES3+

RegExp exec()

Supported in Chrome, Firefox, Safari, Edge, Internet Explorer, and all Node.js versions. Core regex API.

99% Universal API
Google Chrome Supported · Desktop & Mobile
Full support
Mozilla Firefox Supported · Desktop & Mobile
Full support
Apple Safari Supported · macOS & iOS
Full support
Microsoft Edge Supported · Chromium
Full support
Internet Explorer No native support · Use a polyfill
Polyfill
Opera Supported · Modern versions
Full support
Samsung Internet Supported · Android
Full support
Bun Supported · JavaScript runtime
Supported
Deno Supported · JavaScript runtime
Supported
Node.js Supported · Server runtime
Supported
Android WebView Supported · Modern WebView
Full support
RegExp exec() Excellent

Bottom line: Safe everywhere. Remember null checks and use the g flag when looping for all matches.

Conclusion

exec() is the workhorse for running regular expressions and reading capture groups. Use it when you need match text, group values, and position data; use test() for quick yes/no checks; and loop with the g flag to walk every match.

Next, learn the global property to understand how the g flag and lastIndex interact, or review constructor for RegExp type checks.

💡 Best Practices

✅ Do

  • Guard with if (result !== null) before reading slots
  • Use capture groups to name logical parts of a match
  • Loop global regexes with while ((m = re.exec(s)) !== null)
  • Reset lastIndex before reusing a global regex
  • Log the full result while debugging patterns

❌ Don’t

  • Assume exec() always returns an array
  • Loop a non-global regex expecting new matches
  • Share one global regex across concurrent code without resetting
  • Use exec() when test() alone suffices
  • Forget to escape user input in dynamic patterns

Key Takeaways

Knowledge Unlocked

Five things to remember about exec()

Match strings with full detail and capture groups.

5
Core concepts
🔢 02

[0]

Full match.

Output
🔖 03

[1]…

Groups.

Capture
04

null

No match.

Guard
🔄 05

g + loop

All matches.

Iterate

❓ Frequently Asked Questions

An array-like result when a match is found, or null when there is no match. Index 0 is the full match; indexes 1, 2, … hold capture groups. The result also has index (start position) and input (original string).
test() returns only true or false. exec() returns detailed match data—full text, groups, and position—so you can process captures.
With a global regex, match() returns all matches at once (without groups in the array). exec() returns one match per call and is the standard way to read capture groups while iterating.
On a global regex, each exec() call continues from lastIndex. A while loop collects every match until exec() returns null.
It returns null. Always check for null before reading result[0] or capture groups.
No. exec() is read-only. It searches the string you pass in and returns match information without mutating the input.
Did you know?

The classic loop while ((m = /pat/g.exec(str)) !== null) is how many JavaScript engines implement String.prototype.matchAll behavior under the hood for global regexes with capture groups.

Continue to RegExp global

Learn how the global flag enables repeated matching with lastIndex.

global property tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful