8

This will alert 23.

alert(parseInt('23 asdf'));

But this will not alert 23 but alerts NaN

alert(parseInt('asdf 23'));

How can I get number from like 'asd98'?

2
  • 1
    what behaviour is intended when you have a string which contains multiple numbers ? e.g "a24b30c90" Commented Sep 10, 2013 at 7:02
  • I want to get number value and set it to other element. Commented Sep 10, 2013 at 7:03

5 Answers 5

20

You can use a regex to get the first integer :

var num = parseInt(str.match(/\d+/),10)

If you want to parse any number (not just a positive integer, for example "asd -98.43") use

var num = str.match(/-?\d+\.?\d*/)

Now suppose you have more than one integer in your string :

var str = "a24b30c90";

Then you can get an array with

var numbers = str.match(/\d+/g).map(Number);

Result : [24, 30, 90]

For the fun and for Shadow Wizard, here's a solution without regular expression for strings containing only one integer (it could be extended for multiple integers) :

var num = [].reduce.call(str,function(r,v){ return v==+v?+v+r*10:r },0);
Sign up to request clarification or add additional context in comments.

6 Comments

Usually not a fan of regex but looks like not much choice in this case. Nice! :)
@ShadowWizard You do have a choice. Do you like my edit ? ;)
That last code block is beautiful, but it terrifies me for some reason...(no, I have no idea why.)
@DavidThomas Well... I would not accept it in one of my applications without strong justifications...
Lol! Never intended for such a thing but glad I was part of this! ;)
|
3
parseInt('asd98'.match(/\d+/))

Comments

3
function toNumeric(string) {
    return parseInt(string.replace(/\D/g, ""), 10);
}

1 Comment

You still have to parse it to get a number instead of a string. And it works only for a limited set of characters while you could have something more general with /\D/g
1

You have to use regular expression to extract the number.

var mixedTextAndNumber= 'some56number';
var justTheNumber = parseInt(mixedTextAndNumber.match(/\d+/g));

Comments

0
var num = +('asd98'.replace(/[a-zA-Z ]/g, ""));

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.