Why does
"$1 $2 $3".match(/\$(\d+)/g)
return
["$1", "$2", "$2"]
, not
["1", "2", "3"]
?
If I remove the global flag, it will give me the match and the captured match:
["$1", "1"]
but only one.
Is there a way to do a reg ex capture to not give me this?
Even putting in a non-capturing parentheses around the $ gives me the same results, eg:
"$1 $2 $3".match(/(?:\$)(\d+)/g)
If you use a capturing group in your regex (e.g. parens), then you can’t get multiple matches with the
gflag the way you are trying to do it because the.match()function can’t return two dimensions of data (a list of capturing groups for each time it matched). It could have been designed to do that, but it wasn’t so in order to get that info, you have to loop and call.exec()multiple times where you get all the data from each successive match each time you call it.Getting this data using
.exec()looks like this: