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

Gid*_*eon 9 javascript jquery

我试图动态调整输入的数值以包括千位分隔符

这是我的代码:

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);" />
Run Code Online (Sandbox Code Playgroud)

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

我出错的任何想法?如果有一个jQuery解决方案,我已经在我的网站上使用它了.

phe*_*atd 14

试试这个正则表达式:

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

  • 完全相同的结果,只是在第4次之后删除它 (4认同)

Isi*_*dum 8

要添加千位分隔符,您可以对这些调用进行字符串拆分,反向和替换:

function addThousandsSeparator(input) {
    var output = input
    if (parseFloat(input)) {
        input = new String(input); // so you can perform string operations
        var parts = input.split("."); // remove the decimal part
        parts[0] = parts[0].split("").reverse().join("").replace(/(\d{3})(?!$)/g, "$1,").split("").reverse().join("");
        output = parts.join(".");
    }

    return output;
}

addThousandsSeparator("1234567890"); // returns 1,234,567,890
addThousandsSeparator("12345678.90"); // returns 12,345,678.90
Run Code Online (Sandbox Code Playgroud)


Dil*_*son 5

尝试

<input type="text" onkeyup="this.value=addCommas(this.value);" />
Run Code Online (Sandbox Code Playgroud)

代替.由于该功能使用文本而不是数字.