gpt4 book ai didi

javascript - 添加逗号作为千位分隔符(javascript) - 输出被删除

转载 作者:可可西里 更新时间:2023-11-01 02:50:29 27 4
gpt4 key购买 nike

我正在尝试动态调整输入的数值以包含千位分隔符

这是我的代码:

function addCommas(nStr) {
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}


<input type="number" onkeyup="this.value=addCommas(this.value);" />

但是当我在 4 之后输入数字时,该字段被清除。

有什么地方出错了吗?如果有 jQuery 解决方案,我已经在我的网站上使用了。

最佳答案

试试这个正则表达式:

function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

关于javascript - 添加逗号作为千位分隔符(javascript) - 输出被删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13621769/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com