davidgale davidgale - 4 months ago 7
Javascript Question

Named capturing groups in JavaScript regex?

As far as I know there is no such thing as named capturing groups in JavaScript. What is the alternative way to get similar functionality?


Generally, you can do everything with normal (numbered) capturing groups that you can do with named capturing groups, you just need to keep track of the numbers.

There are only two "structural" advantages of named capturing groups I can think of:

  1. In some regex flavors (.NET and JGSoft, as far as I know), you can use the same name for different groups in your regex (see here for an example where this matters). But most regex flavors do not support this functionality anyway.

  2. If you need to refer to numbered capturing groups in a situation where they are surrounded by digits, you can get a problem. Let's say you want to add a zero to a digit and therefore want to replace (\d) with $10. In JavaScript, this will work (as long as you have fewer than 10 capturing group in your regex), but Perl will think you're looking for backreference number 10 instead of number 1, followed by a 0. In Perl, you can use ${1}0 in this case.

Other than that, named capturing groups are just "syntactic sugar". It helps to use capturing groups only when you really need them and to use non-capturing groups (?:...) in all other circumstances.

The problem with JavaScript is that it does not support verbose regexes which would make the creation of readable, complex regular expressions a lot easier.