从JavaScript中的字符串中剥离逗号和非数字字符 [英] Stripping commas and non-numeric characters from string in javascript

查看:85
本文介绍了从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));
    }   
}

这篇关于从JavaScript中的字符串中剥离逗号和非数字字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆