使用正则表达式去除破折号,逗号和非数字字符,但是将数字加在一起时,破折号未正确去除

时间:2019-04-11 14:30:26

标签: javascript jquery

我使用下面的JS来去除逗号,破折号和任何非数字字符。但是,如果我说“ ---”,那么该数字仍然不能正确添加,而是变为负数。这让我难过。谁能看到发生了什么事?谢谢,它在var result块中。

    var $recurringCostField = $('#am_attribute_campaign_addon_monthly_cost_value');
    var $recurringTotalCostField = $('#am_attribute_campaign_addon_total_monthly_cost_value');
    var $totalRetailAmountField = $('#am_total_retail_amount');
    var $totalRetailAmountFieldLabel = $('label[for=am_total_retail_amount]');
    var $oneTimeCostField = $('#am_attribute_campaign_addon_one_time_cost_value');

//Calculate One time cost and total recurring cost
function calcTotalRetailVal() {
    var num1 = $oneTimeCostField.val();
    var num2 = $recurringTotalCostField.val();
    var result = parseFloat(num1.replace(/(,|[^\d.-]+)+/g, '')) + parseFloat(num2.replace(/(,|[^\d.-]+)+/g, ''));

            if (!isNaN(result)) {
                $totalRetailAmountField.text('$' + result.toFixed(2));
            }   
        }
        calcTotalRetailVal();
                $oneTimeCostField.on("keydown keyup", function() {
                    calcTotalRetailVal();
             });
             $recurringTotalCostField.on("keydown keyup", function() {
                calcTotalRetailVal();
             });

0 个答案:

没有答案