1
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!

4
  • For something that simple I think a couple of trivial string calls are better than an regex. You could also; parseInt(amount.substr(1), 10) Commented Jan 31, 2014 at 17:47
  • possible duplicate of how to extract numbers from string using Javascript? and many more. Commented Jan 31, 2014 at 17:49
  • Oh so horrible: var amount = "(21)"; var num = new Function("return " + amount + ";")();, but I had to share. Commented Jan 31, 2014 at 17:57
  • @epascarello well for that matter, var num = eval(amount); -- but yeah, I wouldn't recommend that. Commented Jan 31, 2014 at 19:57

1 Answer 1

4

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);
Sign up to request clarification or add additional context in comments.

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.