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

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");
}

All lessons in this course
- Regex basics — literals, test, anchors, and flags
- Groups, Captures, and Replace
- Validation & small pitfalls