如何在每3位数字后添加逗号?

时间:2018-06-26 14:03:29

标签: javascript jquery regex

这是我的代码的简化:

$("#annual_sales").on('keyup', function () {
    $(this).val( $(this).val().replace(/(\d{3})/g, "$1,") );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="annual_sales" type="text" />

我试图在每3位数字后添加一个逗号。

The patterns works well here ,但是您可以看到(在上面的代码段中)在JS中不起作用。知道怎么了吗?

6 个答案:

答案 0 :(得分:2)

由于该事件多次触发,因此无法在此处工作,然后您需要在每次事件触发时删除以前添加的逗号的第一个,并在所需位置添加新的逗号:

$(this).val().replace(/,/g,'').replace(/(\d{3})/g, "$1,")

**注意:**我建议改用input事件,因为它在跟踪使用输入时效率更高,还可以调整正则表达式,因此不会在行末添加逗号:

/(\d{3}(?!$))/g

$("#annual_sales").on('input', function() {
  $(this).val($(this).val().replace(/,/g, '').replace(/(\d{3}(?!$))/g, "$1,"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="annual_sales" type="text" />

答案 1 :(得分:1)

在当前模式(\d{3})中,您在匹配3位数字之后以及在3位数字之后已经有逗号的情况下添加了逗号。

您可能要做的是使用负数lookahead (?!,)匹配3位数字,以断言以下不是逗号:

(\d{3}(?!,))

$("#annual_sales").on('keyup', function() {
  $(this).val($(this).val().replace(/(\d{3}(?!,))/g, "$1,"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="annual_sales" type="text" />

如果您不希望在行末使用逗号,则可以在否定前瞻中使用一种替代方式,断言其后的内容既不是逗号也不是行(\d{3}(?!,|$))的末尾

$("#annual_sales").on('keyup', function() {
  $(this).val($(this).val().replace(/(\d{3}(?!,|$))/g, "$1,"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="annual_sales" type="text" />

答案 2 :(得分:1)

您需要像下面这样预先从值中删除之前添加的“,”。

$("#annual_sales").on('keyup', function () {
    $(this).val($(this).val().replace(new RegExp(",", "g"), ""));
    $(this).val( $(this).val().replace(/(\d{3})/g, "$1,") );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="annual_sales" type="text" />

答案 3 :(得分:0)

大概是要从右侧添加这些逗号作为美式数字分隔符。这段代码将通过在添加逗号前后进行反转来做到这一点。

var addCommas = s => s.split('').reverse().join('')
    .replace(/(\d{3})/g, '$1,').replace(/\,$/, '')
    .split('').reverse().join('')  // Really want String.prototype.revese!

$("#annual_sales").on('keyup', function () {
    $(this).val( addCommas($(this).val().replace(/\,/g, '')) );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="annual_sales" type="text" />

(通过转换为数组进行反向操作确实让我想要一种String.prototype.reverse方法。)

如果必须支持小数点后两位以上的数字,则此功能将需要进行其他工作。

答案 4 :(得分:0)

老实说,我认为实现这一目标的最好,最直接的方法是不要直接依靠正则表达式替换来添加逗号。因为正则表达式从左到右运行,并且在这种情况下,我们想从右到左进行解析,所以实际上没有简单的方法可以做到这一点。

相反,我建议使用javascript来完成繁重的工作:

$("#annual_sales").on('keyup', function () {
    var value = $(this).val();
    var match = value.match(/[0-9,.$]+/);    // Match any chars seen in currency
    var new_value = "";
    if (match) {
        var digits = match[0].match(/\d/g);  // Match single digits into an array
        if (digits.length > 3) {
            for (var i = digits.length - 3; i > 0; i = i - 3) {
                // Start at 3 less than the length,
                // continue until we reach the beginning,
                // step down at intervals of 3

                digits.splice(i, 0, ",");    // Insert a comma
            }
            new_value = digits.join("");
            $(this).val(new_value);
        }
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="annual_sales" type="text" />

使用此功能,您可以扩展其对货币值的处理,例如在值前加一个美元符号,或者拆分小数点并在其后强制两位。

编辑: Scott的答案是我在这里建议的简短版本(顺便说一句,很好)。

答案 5 :(得分:0)

好吧,你可以使用这个简单的技巧:

tooltips: {
    callbacks: {
        label: function(tooltipItem, data) {
            let label = data.labels[tooltipItem.index];
            let value = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
            return ' ' + label + ' : ' + value.replace(/(.)(?=(.{3})+$)/g,"$1,");
        }
    }
}
相关问题