Course contentsShow
← JavaScript
Lesson 1699 of 2,72336. Regular ExpressionsFree lesson

What Are Capture Groups?

Learn how parentheses create capture groups that extract and store matched substrings from regex patterns.

What Are Capture Groups?

You'll learn how parentheses in regex create capture groups that extract and store matched substrings for later use.

The Core Idea

When you wrap part of a regex pattern in parentheses, you create a capture group. Think of it as marking a section of your match with a highlighter—not only does the pattern match, but JavaScript remembers that specific part separately.

Without capture groups, regex just tells you "yes, this matches" or "no, it doesn't." With capture groups, you can say "yes it matches, and here are the pieces I care about."

How They Work

Consider matching a date pattern like 12/25/2023. You could use /\d{2}\/\d{2}\/\d{4}/ to match it, but that just confirms it's a valid format. If you wrap parts in parentheses: /(\d{2})\/(\d{2})\/(\d{4})/, you create three capture groups—one for month, one for day, one for year.

When you use exec() or match(), the result includes:

  • Index 0: the entire match ("12/25/2023")
  • Index 1: first capture group ("12")
  • Index 2: second capture group ("25")
  • Index 3: third capture group ("2023")

Real-World Analogy

Imagine searching a document for phone numbers. You don't just want to find them—you want to extract the area code, prefix, and line number separately. Capture groups let you do exactly that in one pattern.

When to Use Them

Use capture groups whenever you need to:

  • Extract specific parts of a match
  • Reference matched substrings later (in replacements or logic)
  • Break complex patterns into meaningful pieces

Key Takeaway: Parentheses in regex create capture groups that store matched substrings separately, turning pattern matching from a yes/no question into structured data extraction.