Create a named group in a JavaScript RegExp

To create a named group in a JavaScript RegExp, we can use the (?<name>...) syntax:

ts
const text = 'foo bar foo'
const regex = /(?<wanted>bar)/
 
const result = regex.exec(text)
if (result === null) {
throw new Error('No match')
}
 
const wantedGroup = result.groups?.wanted
const wantedGroup: string | undefined

Join my mailing list

Get monthly insights, personal stories, and in-depth information about what I find helpful in web development as a freelancer.

Email advice once a month + Free XState report + Free course on XState

Want to see what it looks like? View the previous issues.

I value your privacy and will never share your email address.