In regular expressions, you can give
names to capturing groups. There is
a special syntax for this. Here it
is: (?<name>pattern)
,
where a pattern
is the regex
and a name
is the name of
the capturing group.
Let's look at an example. Let's say we have the following string:
let str = '2025-10-29';
Let's make a regex in which the capturing groups are named:
let reg = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
Let's apply a regex to our string:
let res = str.match(reg);
The capturing groups data will go into
the groups
property of the result
as an object:
console.log(res.groups);
We can access each object element separately:
console.log(res.groups.year); // 2025
console.log(res.groups.month); // 10
console.log(res.groups.day); // 29
Given a string with time:
let str = '12:59:59';
Put hours, minutes and seconds into separate named capturing groups.