jquery - Stripping commas and non-numeric characters from string in javascript - Stack Overflow

should be simple but RegExs never seem to be :). Can anyone help on how to strip both a ma and any non-

should be simple but RegExs never seem to be :). Can anyone help on how to strip both a ma 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));
    }   
}

should be simple but RegExs never seem to be :). Can anyone help on how to strip both a ma 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));
    }   
}
Share Improve this question edited Apr 10, 2019 at 20:43 erics15 asked Apr 10, 2019 at 20:28 erics15erics15 6271 gold badge9 silver badges28 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4
const clearText = plainText.replace(/\D/g,'')

\D will match all non-digits, but if you need to preserve dots and dashes:

replace(/[^\d.-]/g, '')

You should use this regex /(,|[^\d.-]+)+/g to detect ma 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.

I rewrite your code.

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

With a regexp. num1.replace(/[^0-9.]/, '')

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745394888a4625833.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信