Why does regex get the value twice using match in Javascript?

I have the following code:

var str = "$123";
var re = /(\$[0-9]+(\.[0-9]{2})?)/;
var found = str.match(re);

alert(found[1]);
alert(found[0]);

I am trying to understand why it found [0] and found [1] will contain $ 123. Why does this happen twice?

I would like to get all the “potential” prices only one, so for example, if I have this line:

var str = "$123 $149 $150"; This will:

found[0] = $123
found[1] = $149
found[2] = $150

And it would be that the array found would not have any more matches.

What's going on here? What am I missing?

+4
source share
3 answers

This is because of the bracket around the whole expression: it defines the captured group.

If you do not use the flag g, it matchreturns to the array:

  • whole line if it matches the pattern
  • ()

- .

,

"$123 $149 $150".match(/\$\d+(\.\d{0,2})?/g)

["$123", "$149", "$150"]

: MDN

+6

- .

, , .

, . .


FYI, , , ?: .

var re = /(?:\$[0-9]+(\.[0-9]{2})?)/;

, , ?:.

+6

Add a flag gat the end of your regular expression. Otherwise, only the first match will be cleared. When gsubgroups are not fixed. They do not need you; the outer brackets in your regex actually do nothing.

var re = /\$[0-9]+(\.[0-9]{2})?/g;

You can explicitly prohibit capturing a subgroup with (?:, but that doesn't matter with the flag g.

+2
source

All Articles