从JavaScript中的字符串中剥离逗号和非数字字符

问题描述:

应该很简单,但是RegExs似乎从来不是:).谁能帮忙从字符串中去除逗号和任何非数字字符?谢谢.它在var result块中.显然,当您将运算符输入数字时,它会炸毁num1num2.我还需要去除所有破折号.

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));
    }   
}