Return only numbers from string

For this task the easiest way to do it will be to us regex :)

var input = "Rs. 6,67,000";
var res = input.replace(/\D/g,'');
console.log(res); // 667000

Here you can find more information about how to use regex:

https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions

I hope it helped :)

Regards


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.


You can make a function like this

function justNumbers(string) {
  var numsStr = string.replace(/[^0-9]/g, '');
  return parseInt(numsStr);
}

var input = "Rs. 6,67,000";
var number = justNumbers(input);
console.log(number); // 667000

Tags:

Javascript