这是我的代码的简化:
$("#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位数字后加一个逗号。
,但正如您所看到的(在上面的代码片段中),它在JS中不起作用。知道出什么问题了吗?
发布于 2018-06-26 22:11:17
在您当前的pattern (\d{3})
中,您可以在匹配3个数字之后添加一个逗号,并且当3个数字后面已经有一个逗号时也是如此。
您可能要做的是使用负lookahead (?!,)
匹配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" />
发布于 2018-06-26 22:05:58
这里不起作用,因为事件会多次触发,然后你需要在每次事件触发时删除之前添加的第一个逗号,并在所需的位置添加新的逗号:
$(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" />
发布于 2018-06-26 22:12:06
您需要将之前添加的",“从预先的值中去掉,如下所示。
$("#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" />
https://stackoverflow.com/questions/51044838
复制相似问题