Groups, choices and lazy matching
Capturing groups and backreferences
Goal: Extract parts of a match and reuse them with \1 and $1 · 10 min
Every pair of ordinary parentheses captures the text it matched and numbers it from left to right: group 1, group 2, and so on (counted by the opening parenthesis).
const m = "2024-05-17".match(/(\d{4})-(\d{2})-(\d{2})/);
// m[0] = "2024-05-17" m[1] = "2024" m[2] = "05" m[3] = "17"
Named groups make this readable: (?<year>\d{4}), then m.groups.year.
In the replacement text of replace, $1, $2 … insert the captured text. Reordering a date is a one-liner: "2024-05-17".replace(/(\d{4})-(\d{2})-(\d{2})/, "$3.$2.$1") gives "17.05.2024".
Backreferences \1, \2 inside the pattern itself require the same text again: (\w)\1 finds a doubled letter such as "ll" in "hello"; \b(\w+) \1\b finds a repeated word like "the the".
Worked example: Swapping first and last name
- Input: "Lovelace, Ada".
- Pattern with two groups:
/(\w+), (\w+)/captures "Lovelace" as $1 and "Ada" as $2. - Replacement "$2 $1" gives "Ada Lovelace".
console.log("Lovelace, Ada".replace(/(\w+), (\w+)/, "$2 $1"));Output:
Ada Lovelace