1

I need to extract number from string like

<p id="example">etc etc(5)</p>
<p id="example2">etc etc(-5)</p>

I'm using this code

alert($("#example").text().match(/\((\d+)\)/)[1]);

It's work fine if the number is positive but in the case of a negative number get error

Uncaught TypeError: Cannot read property '1' of null

please help me about that thank's

0

2 Answers 2

8

Try this:

.match(/\((-?\d+)\)/)[1]

-? says "optional minus".

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

3 Comments

\-? would probably be a safer habit to develop, as the hyphen is a reserved char which is used to specify character ranges inside []
@Cheekysoft: I was just answering that question today. The grammar inside [] is very different than outside; I see no reason to pollute one with artifacts of the other.
meh, just a question of taste really. I like it when rules can be boiled down to the simpler set, especially when teaching. Personally i find it better to get into the practice of knowing the reserved characters and always quoting them, as it is completely safe to do so. The fact that it is unnecessary doesn't interest me. It's easier to follow the same methodology even if it is strictly "not required". ...But i'm not here to continue a religious war :-) I have at least as much respect for your POV as my own.
1

Try this instead:

alert($("#example").text().match(/\((-?\d+)\)/)[1]);​

That will capture negative numbers as well.

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.