Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get numeric value from string?

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'?

like image 829
Navin Rauniyar Avatar asked Sep 10 '13 06:09

Navin Rauniyar


People also ask

How do I extract numbers from a string?

The number from a string in javascript can be extracted into an array of numbers by using the match method. This function takes a regular expression as an argument and extracts the number from the string. Regular expression for extracting a number is (/(\d+)/).

How do I extract numeric value from text in Excel?

Extract Numbers from String in Excel (using VBA) Since we have done all the heavy lifting in the code itself, all you need to do is use the formula =GetNumeric(A2). This will instantly give you only the numeric part of the string. Note that since the workbook now has VBA code in it, you need to save it with .

How do I find the numeric value of a string in Python?

To find numbers from a given string in Python we can easily apply the isdigit() method. In Python the isdigit() method returns True if all the digit characters contain in the input string and this function extracts the digits from the string. If no character is a digit in the given string then it will return False.

Can a string hold a numeric value?

One of the most widely used data types is a string. A string consists of one or more characters, which can include letters, numbers, and other types of characters.


2 Answers

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);
like image 110
Denys Séguret Avatar answered Sep 19 '22 17:09

Denys Séguret


parseInt('asd98'.match(/\d+/))
like image 40
at. Avatar answered Sep 19 '22 17:09

at.