Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return only numbers from string

Tags:

javascript

I have a value in Javascript as

var input = "Rs. 6,67,000" 

How can I get only the numerical values ?

Result: 667000

Current Approach (not working)

var input = "Rs. 6,67,000"; var res = str.replace("Rs. ", "").replace(",",""); alert(res);  Result: 667,000 
like image 659
priyanka.sarkar Avatar asked Jun 02 '15 22:06

priyanka.sarkar


People also ask

How do I extract numbers from a string 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 you only extract a number from 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.


1 Answers

This is a great use for a regular expression.

    var str = "Rs. 6,67,000";      var res = str.replace(/\D/g, "");      alert(res); // 667000

\D matches a character that is not a numerical digit. So any non digit is replaced by an empty string. The result is only the digits in a string.

The g at the end of the regular expression literal is for "global" meaning that it replaces all matches, and not just the first.

This approach will work for a variety of input formats, so if that "Rs." becomes something else later, this code won't break.

like image 80
Alex Wayne Avatar answered Oct 07 '22 19:10

Alex Wayne