最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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.]/, '')

发布评论

评论列表(0)

  1. 暂无评论