Create a named group in a JavaScript RegExp

Published on


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 new articles directly in your inbox.

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