• Home
  • Jobs
  • coursesAndChallenges
  • Teachers
  • For business
  • Blog
  • ES/EN

0

37
Views
Return only numbers from string

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
about 1 month ago ·

Santiago Trujillo

3 answers
Answer question

0

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.

about 1 month ago · Santiago Trujillo Report

0

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

about 1 month ago · Santiago Trujillo Report

0

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

about 1 month ago · Santiago Trujillo Report
Answer question
Remote jobs
Loading

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Startups
Legal
Terms and conditions Privacy policy
© 2022 PeakU Inc. All Rights Reserved.