user533178
user533178

Reputation: 77

Extract number from string with jquery

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

Upvotes: 1

Views: 6912

Answers (2)

Amadan
Amadan

Reputation: 198526

Try this:

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

-? says "optional minus".

Upvotes: 8

Igor
Igor

Reputation: 34021

Try this instead:

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

That will capture negative numbers as well.

Upvotes: 1

Related Questions