Skip to content

How to use named capture group in Javascript regex

How to use named capture group in Javascript regex

In this post we will see how can named capture group and use the name in code. It makes the code more readable and maintenable. We will take an example where we will get price and quantity information from a string.


Without named capture group

const priceQuantityRegex = /\$(\d) for (\d)/;
const priceQuantityStr = 'Price $8 for 2';
const priceQuantityGroup = re.exec( priceQuantityRegex );

console.log( priceQuantity[1] );    // 8
console.log( priceQuantity[2] );    // 2

With named capture group

const priceQuantityRegex = /\$(?<price>\d) for (?<quantity>\d)/;
const priceQuantityStr = 'Price $8 for 2';
const priceQuantityGroup = re.exec( priceQuantityRegex );

console.log( priceQuantityGroup.groups.price );       // 8
console.log( priceQuantityGroup.groups.quantity );    // 2

Conclusion

Hope this helps you to understand about named captured groups. See you in my next post. Till then enjoy coding 🙂

Further Readings

Javascript Regex

How to get word, number, whitespace using Javascript regex

Please share