I have a two different different numbers, each with a dollar sign. I want to get the two numbers separately.
JavaScript:
function price_range(id){
//var str = $('#'+id).val();
var str = '$75 - $300';
var removeDollar = str.replace(/\$/,'');
alert(removeDollar);
}
<a href="javascript:;" onclick="price_range('amount')">Click Here</a>
I have a two different different numbers, each with a dollar sign. I want to get the two numbers separately.
JavaScript:
function price_range(id){
//var str = $('#'+id).val();
var str = '$75 - $300';
var removeDollar = str.replace(/\$/,'');
alert(removeDollar);
}
<a href="javascript:;" onclick="price_range('amount')">Click Here</a>
The above code only replaces the first dollar sign, but I have two dollar signs with number. How can I get 75
and 300
separately?
3 Answers
Reset to default 8You can just get all the numbers from the string, like this
console.log('$75 - $300'.match(/(\d+)/g));
# [ '75', '300' ]
Note: This simple RegEx will match and get all the numbers, even if there are more than 2 numbers in the string. But for this simple task, you don't need a plicate RegEx.
If you want to fix your program, you can do it like this
console.log('$75 - $300'.replace(/\$/g, '').split(/\s*-\s*/));
# [ '75', '300' ]
replace(/\$/g, '')
will replace $
symbol from the string and then you can split the string based on \s*-\s*
, which means zero or more white space characters, followed by -
, and followed by zero or more white space characters.
You could extend the regular expression in the .replace()
function to have a global flag g
:
str.replace(/\$/g,'');
The whole script would work like this, but will be specific to removing the $ sign.
function price_range(id){
//var str = $('#'+id).val();
var str = '$75 - $300';
var removeDollar = str.replace(/\$/g,'');
alert(removeDollar);
}
<a href="javascript:;" onclick="price_range('amount')">Click Here</a>
An option would be to extract numbers with a regular expression like this:
var str = '$70 - $300 some other 500%';
var arrOfStrings = str.match(/\d+/gi);
// arrOfStrings = ['70', '300', '500']
var arrOfNrs = arrOfStrings.map(function (e) {
return parseInt(e);
}); // map not supported by all browsers. you can use the _.map from underscorejs
// arrOfNrs = [70, 300, 500]