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?
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]
本文标签: regexHow to get only number in javascriptStack Overflow
版权声明:本文标题:regex - How to get only number in javascript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745450568a2658862.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论