2

我看到了这个漂亮的脚本来为 js 数字添加千位分隔符:

function thousandSeparator(n, sep)
{
    var sRegExp = new RegExp('(-?[0-9]+)([0-9]{3})'),
        sValue = n + '';
    if(sep === undefined)
    {
        sep = ',';
    }
    while(sRegExp.test(sValue))
    {
        sValue = sValue.replace(sRegExp, '$1' + sep + '$2');
    }
    return sValue;
}

用法 :

thousandSeparator(5000000.125, '\,') //"5,000,000.125"

但是,我无法接受while 循环

我正在考虑将正则表达式更改为:'(-?[0-9]+)([0-9]{3})*' 星号...

但是现在,我该如何应用替换语句?

现在我将拥有$1并且$2..$n

如何增强替换功能?

ps代码取自这里http://www.grumelo.com/2009/04/06/thousand-separator-in-javascript/

4

5 回答 5

7

不需要使用replace,你可以直接添加toLocaleString

console.log((5000000.125).toLocaleString('en'));

更多信息:https ://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString

于 2018-04-09T10:06:11.927 回答
5

你的假设

现在我将有 $1 和 $2..$n

是错的。你有两组,因为你有两组括号。

    (-?[0-9]+)([0-9]{3})*
1.  ^^^^^^^^^^
2.            ^^^^^^^^^^

然后你重复第二组。如果第二次匹配,它会覆盖第一次匹配的结果,当它匹配第三次时,它会覆盖......

这意味着当匹配完成时,$2包含该组的最后一个匹配的值。

第一种方法

(\d)(?=(?:[0-9]{3})+\b)

并替换为

$1,

在 Regexr 上查看

它的缺点是它确实在点的右侧也插入了逗号。(我正在做。)

第二种方法

(\d)(?:(?=\d+(?=[^\d.]))(?=(?:[0-9]{3})+\b)|(?=\d+(?=\.))(?=(?:[0-9]{3})+(?=\.)))

并替换为

$1,

在 Regexr 上查看

所以现在它变得有点复杂了。

(\d)                   # Match a digit (will be reinserted)
(?:
    (?=\d+(?=[^\d.]))  # Use this alternative if there is no fractional part in the digit
    (?=(?:\d{3})+      # Check that there are always multiples of 3 digits ahead
    \b)                # Till a word boundary
    |                  # OR
    (?=\d+(?=\.))      # There is a fractional part
    (?=(?:\d{3})+      # Check that there are always multiples of 3 digits ahead
    (?=\.))            # Till a dot
)

问题: 如果后面没有字符串的结尾,它也匹配小数部分。

于 2012-05-16T05:43:32.923 回答
1

这是一个丑陋的脚本来对比你漂亮的脚本。

10000000.0001 .toString().split('').reverse().join('')
.replace(/(\d{3}(?!.*\.|$))/g, '$1,').split('').reverse().join('')

由于我们没有lookbehinds,我们可以通过反转字符串并使用lookaheads来作弊。

在这里,它再次以更可口的形式出现。

function thousandSeparator(n, sep) {

    function reverse(text) {
        return text.split('').reverse().join('');
    }

    var rx = /(\d{3}(?!.*\.|$))/g;

    if (!sep) {
        sep = ',';
    }

    return reverse(reverse(n.toString()).replace(rx, '$1' + sep));

}
于 2012-05-16T05:18:54.137 回答
1

这个怎么样:

result = "1235423.125".replace(/\B(?=(\d{3})+(?!\d))/g, ',') //1,235,423.125
于 2016-12-16T16:46:25.713 回答
0

试试这个:

result = subject.replace(/([0-9]+?)([0-9]{3})(?=.*?\.|$)/mg, "$1,$2");

在这里测试

于 2012-05-16T05:28:45.373 回答