Milos Cuculovic
Milos Cuculovic

Reputation: 20223

Javascript and RegEx: match function returns an array

I have a string:

var doi_id= "10.3390/metabo1010001"

And I would like to match only the first serie of digits from the end.

For that, I am using this regEx:

var doinumericpart = doi_id.match(/(\d*)$/);

The "problem" (or not) is that doinumericpart returns

1010001,1010001

instead of 1010001 and I don't know why.

When I am trying this regex here: http://regexr.com?31htm everything seems to work fine.

Thank you very much for the help.

Upvotes: 1

Views: 633

Answers (3)

Stefan
Stefan

Reputation: 114178

match returns the complete match and each capturing group or null if there were no matches.

This is useful if you want to provide some context:

"10.3390/metabo1010001".match(/metabo(\d*)/)
// => ["metabo1010001", "1010001"]
  • metabo1010001 is the whole match
  • 1010001 is the first capturing group

Upvotes: 2

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324640

match() returns an array like it's supposed to. The first element is the whole substring that matched the pattern, then the first one onwards contain the subpatterns.

In your case, just get rid of the () - you don't need them since they enclose the whole pattern.

var doinumericpart = doi_id.match(/\d*$/)[0];

The [0] dereferences the array to give you the exact element you want.

Upvotes: 8

Esailija
Esailija

Reputation: 140230

match returns either null or an array of the matches. The amount of matches depends on how many capturing groups you have in your regex. The item at [1] will be your match so you can do:

var doinumericpart = doi_id.match(/(\d*)$/)[1]; //Access second item in the matches array

Upvotes: 4

Related Questions