1

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.

1
  • try removing the parentheses after \d* and just have \d*$ Commented Jul 16, 2012 at 14:52

3 Answers 3

8

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Select the answer as the accepted answer then :) Give the man some credit
4

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

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.