ChinDave
ChinDave

Reputation: 37

Extract a number from a string? (Javascript)

var amount = "(21)";

How would I go about just getting the number? I have gotten it to work with...

var amountResult = amount.substring(1, amount.length-1);

...but that just feels incorrect.

What's the better, more flexible way to do this if it were not always surrounded by just 2 characters?

Thanks!

Upvotes: 1

Views: 56

Answers (1)

p.s.w.g
p.s.w.g

Reputation: 148980

Using a regular expression is much more flexible:

var amountResult = amount.match(/\d+/)[0];

And to actually turn it into an number:

var amountResult = parseInt(amount.match(/\d+/)[0], 10);

Upvotes: 4

Related Questions