【发布时间】:2012-05-16 05:01:49
【问题描述】:
我看到了这个漂亮的脚本来为 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})*' asterisk...
但是现在,我该如何应用替换语句?
现在我将拥有$1 和$2..$n
如何增强替换功能?
附言代码取自这里http://www.grumelo.com/2009/04/06/thousand-separator-in-javascript/
【问题讨论】:
-
顺便说一句,它在
5000000.125678上失败 ->5,000,000.125,678 -
@zerkms 是的,你说得对。 grumelo.com/2009/04/06/thousand-separator-in-javascript
-
查看this question - 有一个链接to an example 告诉你如何做你正在尝试的事情。
-
@RobI 再次,它仍然有一个while循环。我认为可以找到更好的解决方案....(或没有)...:)
-
@Cylian 我认为我们需要积极向前看
(-?[0-9]+)([0-9]{3})(?=\.)但它不起作用......我的意思是 - 只替换右边有一个点的数字。
标签: javascript regex performance separator