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
Fundamentals
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.
Concept
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.
Foundation
📝 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
Cheat Sheet
⚡ Quick Reference
Goal
Code
Run a match
/pat/.exec(text)
Full match text
result[0]
First capture group
result[1]
Match start index
result.index
No match
null
All matches (global)
while ((m = /pat/g.exec(s)) !== null)
Compare
📋 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
Hands-On
Examples Gallery
Open DevTools Console (F12) or use Try-it links. Every example shows how to read the exec result safely.
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]);
}
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.
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.
Applications
🚀 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.
Important
📝 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().
Compatibility
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 ChromeSupported · Desktop & Mobile
Full support
Mozilla FirefoxSupported · Desktop & Mobile
Full support
Apple SafariSupported · macOS & iOS
Full support
Microsoft EdgeSupported · Chromium
Full support
Internet ExplorerNo native support · Use a polyfill
Polyfill
OperaSupported · Modern versions
Full support
Samsung InternetSupported · Android
Full support
BunSupported · JavaScript runtime
Supported
DenoSupported · JavaScript runtime
Supported
Node.jsSupported · Server runtime
Supported
Android WebViewSupported · Modern WebView
Full support
RegExp exec()Excellent
Bottom line: Safe everywhere. Remember null checks and use the g flag when looping for all matches.
Wrap Up
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.
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
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about exec()
Match strings with full detail and capture groups.
5
Core concepts
📝01
Syntax
regex.exec(s)
API
🔢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.