从JavaScript中的字符串中剥离逗号和非数字字符 [英] Stripping commas and non-numeric characters from string in javascript
问题描述
应该很简单,但是RegExs似乎从来不是:).谁能帮忙从字符串中去除逗号和任何非数字字符?谢谢.它在var result
块中.显然,当您将运算符输入数字时,它会炸毁num1
和num2
.我还需要去除所有破折号.
should be simple but RegExs never seem to be :). Can anyone help on how to strip both a comma and any non-numeric characters from a string? Thanks. It's in the var result
block. Apparently when you put an operator in the number it bombs out.num1
and num2
. I also need to strip out any dashes.
function calcTotalRetailVal() {
var num1 = $oneTimeCostField.val();
var num2 = $recurringTotalCostField.val();
//In the replace method
var result = parseFloat(num1.replace(/,/g, '')) + parseFloat(num2.replace(/,/g, ''));
if (!isNaN(result)) {
$totalRetailAmountField.text('$' + result.toFixed(2));
}
}
推荐答案
您应该使用此正则表达式/(,|[^\d.-]+)+/g
来检测逗号和任何非数字值,例如字符,运算符,组中的空格,并且比单独检测要快.负数(例如-1)和.将包括在内.
You should use this regex /(,|[^\d.-]+)+/g
to detect comma and any non-numeric value such as characters, operators, spaces in the groups and faster than the individual detection. a negative number (ex -1) and . will be included.
我重写了您的代码.
function calcTotalRetailVal() {
var num1 = $oneTimeCostField.val();
var num2 = $recurringTotalCostField.val();
//In the replace method
var result = parseFloat(num1.replace(/(,|[^\d.-]+)+/g, '')) + parseFloat(num2.replace(/(,|[^\d.-]+)+/g, ''));
if (!isNaN(result)) {
$totalRetailAmountField.text('$' + result.toFixed(2));
}
}
这篇关于从JavaScript中的字符串中剥离逗号和非数字字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!