0Pricing
JavaScript Academy · Lesson

Groups, Captures, and Replace

Capture parts of text with groups, use named groups, iterate all matches, and perform safe replacements with backreferences or a function.

Why groups?

Goal: Extract and reshape text.

  • Capture groups: (...)
  • Named groups: (?<name>...)
  • matchAll to loop all results
  • replace with $1 or a function
Groups, Captures, and Replace — illustration 1

Numbered groups

Use (...) to capture parts. Access them by index: m[1], m[2], ...

// Capture YYYY-MM-DD into groups
const r = /(\\d{4})-(\\d{2})-(\\d{2})/;
const m = r.exec("Today: 2025-09-26");
if (m) {
  console.log("year:", m[1], "month:", m[2], "day:", m[3]);
} else {
  console.log("no match");
}
Groups, Captures, and Replace — illustration 2

All lessons in this course

  1. Regex basics — literals, test, anchors, and flags
  2. Groups, Captures, and Replace
  3. Validation & small pitfalls
← Back to JavaScript Academy