Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why regex gets 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 found[0] and found[1] would contain $123. Why does it get it twice?

I would like to get all the "potential" prices just one, so for example if I have this string:

var str = "$123 $149 $150"; It would be:

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

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

What is happening here? What am I missing?

like image 255
Hommer Smith Avatar asked Oct 29 '13 17:10

Hommer Smith


2 Answers

That's because of the parenthesis around the whole expression : it defines a captured group.

When you don't use the g flag, match returns in an array :

  • the whole string if it matches the pattern
  • the captured group(s)

Here the captured group is the whole string.

What you seem to want is

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

which returns

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

Reference : the MDN about regular expressions and flags

like image 91
Denys Séguret Avatar answered Oct 08 '22 10:10

Denys Séguret


The first is the full match.

The second represents the outer subgroup you defined, which is the same as the full match in your case.

That particular subgroup doesn't really seem necessary, so you should be able to remove it. The inner group doesn't have a match for your particular string.


FYI, if you want to use a group, but make it non-capturing, you can add ?: inside the start of it.

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

Again, the group here isn't doing you much good, but it shows the ?: in use.

like image 30
Blue Skies Avatar answered Oct 08 '22 09:10

Blue Skies