Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
74
rated 0 times [  75] [ 1]  / answers: 1 / hits: 157592  / 13 Years ago, sun, march 20, 2011, 12:00:00

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?


More From » regex

 Answers
8

ECMAScript 2018 introduces named capturing groups into JavaScript regexes.


Example:


  const auth = 'Bearer AUTHORIZATION_TOKEN'
const { groups: { token } } = /Bearer (?<token>[^ $]*)/.exec(auth)
console.log(token) // "AUTHORIZATION_TOKEN"

If you need to support older browsers, 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 - which may be cumbersome if the order of capturing group in your regex changes.


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 bigger problem (in my opinion) with JavaScript is that it does not support verbose regexes which would make the creation of readable, complex regular expressions a lot easier.


Steve Levithan's XRegExp library solves these problems.


[#93177] Friday, March 18, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
hakeemabramh

Total Points: 234
Total Questions: 109
Total Answers: 109

Location: Romania
Member since Mon, Jun 6, 2022
2 Years ago
;