JavaScript RegExp exec() Method

Beginner
6 min read
Updated: Oct 2026
3 examples
Live preview

What Is exec()?

RegExp.prototype.exec(string) runs a search and returns match details (full match, groups, position) or null if nothing matches. It is the detailed cousin of test().

Remember
regex.exec(string)

match found → array:
  [0]     full match
  [1…]    capture groups
  .index  start position
  .input  original string

no match → null

with /g: each call advances lastIndex
UsePrefer
Match + groups + positionregex.exec(str)
Yes / no onlyregex.test(str)
All matches (global)Loop exec() until null

How to Use exec()

Create a regex, call exec, then read the result or handle null.

  1. Create a RegExp (literal or new RegExp).
  2. Call regex.exec(string).
  3. If the result is not null, read [0], groups, and .index.
  4. With the g flag, call exec again in a loop until it returns null.
PieceRequired?Role
RegExpYesPattern to search with
stringYesText to search in
Null checkYes in practiceAvoid reading properties on null

Pseudocode

Pseudocode
regex = /pattern/flags
str = text to search

result = regex.exec(str)

if result is null:
    // no match
else:
    full = result[0]
    group1 = result[1]   // if any
    pos = result.index

// with /g flag:
while (result = regex.exec(str)) is not null:
    use result
// lastIndex advances each time

Cheat Sheet

Keep these facts handy while reading match results.

TopicDetail
Syntaxregex.exec(string)
SuccessArray with match + optional groups
Failurenull
result.indexWhere the match starts
result.inputOriginal string
Global /gUses / updates lastIndex
vs test()test → boolean; exec → details

Live Preview

Pick a pattern and see what exec() returns on sample text.

Browser demo of RegExp.prototype.exec — same idea as the examples below.

Result
regex = /cat/i
str = "The Cat sat"

result = regex.exec(str)
→ ["Cat"]
  index: 4
  input: "The Cat sat"

JavaScript Examples

Short, copy-ready snippets. Open DevTools Console, or use Try It Yourself for a live editor.

Example 1 — Basic Match

Get the matched text and its start index.

JavaScript
const regex = /cat/i;
const result = regex.exec("The Cat sat");

console.log(result[0]);     // "Cat"
console.log(result.index);  // 4
console.log(/dog/.exec("The Cat sat")); // null
Try It Yourself

How It Works

  1. Build the pattern. /cat/i matches cat ignoring case.
  2. Run exec. It finds "Cat" inside "The Cat sat".
  3. Read details. result[0] is the full match; index is 4.
  4. Miss case. /dog/ finds nothing → null.

Example 2 — Capture Groups

Read parts of the match with parentheses.

JavaScript
const regex = /(\w+)-(\d+)/;
const result = regex.exec("Code-42");

console.log(result[0]); // "Code-42"
console.log(result[1]); // "Code"
console.log(result[2]); // "42"
Try It Yourself

How It Works

  1. Pattern with groups. (\w+) and (\d+) capture word and digits.
  2. Full match. result[0] is the entire "Code-42".
  3. Group 1. First pair of parentheses → "Code".
  4. Group 2. Second pair → "42".

Example 3 — Global Loop with lastIndex

Collect every match using the g flag.

JavaScript
const regex = /\d+/g;
const str = "A12 B34 C5";
let match;

while ((match = regex.exec(str)) !== null) {
  console.log(match[0] + " @ " + match.index);
}
// "12 @ 1"
// "34 @ 5"
// "5 @ 9"
Try It Yourself

How It Works

  1. Use the g flag. /\d+/g can find more than one number.
  2. Loop exec. Each call continues from lastIndex.
  3. Print each hit. Match text and start index are logged.
  4. Stop on null. When no more matches remain, exec returns null.

Edge Cases & Pitfalls

Check these before relying on exec() in real projects.

null

Always check for null

Reading result[0] when exec returned null throws. Guard with if (result).

lastIndex

Global regex remembers position

With /g, reuse can continue from a stale lastIndex. Reset with regex.lastIndex = 0 when restarting a search.

trap

Zero-length matches can loop forever

Patterns that can match empty strings (e.g. /a*/g on some inputs) need care — advance lastIndex manually if a match has length 0.

vs test

test() also updates lastIndex when global

Do not mix test and exec on the same global regex without resetting lastIndex.

Browser & Runtime Support

RegExp.prototype.exec() is a long-standing core method — available in every JavaScript environment.

✓ Baseline · Widely available

RegExp.prototype.exec()

Supported in all browsers and Node.js versions. Safe for every target with no polyfill.

100% Universal support
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
exec() Universal

Bottom line: Use freely for match details and capture groups. Prefer test() when you only need a boolean.

Performance Notes

ApproachCostBest for
regex.exec(str)One search stepDetails + groups
regex.test(str)One search stepBoolean only (lighter intent)
Global exec loopOne step per matchAll matches with groups

Prefer test() when you do not need groups or position. For many matches with captures, a global exec loop is the classic approach.

Key Takeaways

  • Role: return match details (or null), including groups and index.
  • Safety: always check for null before reading the result.
  • Global: loop exec() with /g until null; watch lastIndex.
  • vs test: use test() for yes/no; exec() for details.

One line: exec() gives you the match, groups, and position — or null when nothing matches.

Frequently Asked Questions

A result array 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.
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 on the input string. On a global or sticky regex it updates lastIndex on the RegExp object.
Use exec() when you need the matched text, capture groups, or the match position. Use test() for a simple yes/no check.

Next: global

Learn how the g flag and lastIndex change matching behavior.

global property →

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.

10 people found this page helpful