0

I think this is a very basic question, but I really can't understand the concept. I have the following regular expression:

var t = '11:59 am';
t.match(/^(\d+)/);

Now, according to my understanding when I print the value I should just get 11 since I am just checking for digits. However, I get 11,11. I have to use 0th element to pick the required value like t.match(/^(\d+)/)[0].

0

2 Answers 2

1

This is because you are using a capture group, (), around the digits. Try replacing this with:

t.match(/^\d+/);

Note: this will still return an array, because that's just what .match() does.

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

2 Comments

Thank you sam.I understand it now. I dint know about the capture group.
Glad I could help. Sorry that, as far as I know, there isn't a good JS regex method to just return a simple string instead of an array of data. /^\d+/.exec(t) will return ['11'] as well.
1

match() always returns an array if there are any matches. Element [0] is the whole match, and element [1] is what is inside the first set of parentheses.

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.