admin管理员组

文章数量:1425782

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?

Share Improve this question edited Mar 9, 2015 at 13:46 thefourtheye 240k53 gold badges466 silver badges501 bronze badges asked Mar 9, 2015 at 12:57 DeveloperDeveloper 2,7068 gold badges45 silver badges65 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 8

You 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]

本文标签: regexHow to get only number in javascriptStack Overflow