For more tips like this, sign up to the weekly newsletter!
Use named capture groups in RegExp
RegExp has a feature called capture groups that you can use to extract information from a string:
/^(\d*)-(\d*)-(\d*)$/.exec("15-2-1963")[1] // 15
The three captured groups are accessible under the indices 1, 2, and 3. The problem with this is it is hard to know what each group means only by looking at the expression. Is the first one the day or the month?
Named capture groups let you give each one a semantic name. To use it, use the (?<name>...)
syntax. Building on the previous example:
/^(?<day>\d*)-(?<month>\d*)-(?<year>\d*)$/
To access the groups, use the .groups
property of the result. This even works with object destructuring:
const {day, month, year} = /^(?<day>\d*)-(?<month>\d*)-(?<year>\d*)$/.exec("15-2-1963").groups;
Now if you need to support a different date format, the groups will stay the same:
/^(?<month>\d*)\/(?<day>\d*)\/(?<year>\d*)$/.exec("2/15/1963").groups.day; // 15