William Becker
William Becker

Reputation: 347

Get only contents from capturing parenthesis of a Regular Expression in Javascript

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)

Upvotes: 3

Views: 147

Answers (1)

jfriend00
jfriend00

Reputation: 707218

If you use a capturing group in your regex (e.g. parens), then you can't get multiple matches with the g flag 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:

var str = "$1 $2 $3", matches;
var allMatches = [];
var reg = /\$(\d+)/g;

while (matches = reg.exec(str)) {
    // matches[1] is each successive match here from your captured group
    allMatches.push(matches[1]);
}
// allMatches will be what you wanted ["1", "2", "3"]

Upvotes: 6

Related Questions