Regex named capture group in Javascript

In this post we will see how can name captured 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 🙂