将数字包裹在角色的左侧

时间:2011-05-02 19:06:00

标签: javascript jquery regex

为了在数字字符串中添加逗号我正在使用以下内容:

someNum.toString().replace(/\B(?=(?:\d{3})+(?!\d))/g, ",")

我需要做一件额外的事情。我需要将所有内容包装在逗号的左侧(所有数字代表span标记中的数千或以上,以便为这些数字着色。

因此,如果someNum42221,则输出为<span class="someColorClass">42</span>,221,如果someNum221,则输出为221

谢谢!

4 个答案:

答案 0 :(得分:4)

我不知道它是否是最有效的方式,但这有效:

someNum.toString().replace(/\B(?=(?:\d{3})+(?!\d))/g, ",").replace(/^(.*),(\d+)$/,'<span class="someColorClass">$1</span>,$2')

123456789 = <span class="someColorClass">123,456</span>,789
42221 = <span class="someColorClass">42</span>,221
221 = 221

答案 1 :(得分:0)

假设您从未投入数百万美元,在您最初的替换后,您可以这样做:

someNum = someNum.replace(/(\d*)(,\d{3})/g, '<span class="someColorClass">$1</span>$2');

答案 2 :(得分:0)

有两个正则表达式:

var someNum = 12345;
var commaNum = someNum.toString().replace(/\B(?=(?:\d{3})+(?!\d))/g, ",").replace(/^(\d+),/,"<span>$1</span>,");
alert(commaNum);

如果数以百万计,就会失败,突显数千人。

Example

如果数字可以大于99,999,则可以使用与任何内容匹配的正则表达式。它将在比赛中包含逗号。

var someNum = 12345;
var commaNum = someNum.toString().replace(/\B(?=(?:\d{3})+(?!\d))/g, ",").replace(/^([\d,]+)(,\d{3})/g,"<span>$1</span>$2");
alert(commaNum);

Example

答案 3 :(得分:0)

不同的方法,检查字符串长度...

var num = "432232121678";
var num2 = "221";

function Parse(num)
{
    var thousand = num.substring(0, num.length - 3);
    if (thousand.length > 0)
    {
        return "<span class=\"someColorClass\">" + thousand.replace(/\B(?=(?:\d{3})+(?!\d))/g, ",") + "</span>," + num.substring(num.length - 3)
    }
    return num;
}

Parse(num);
Parse(num2);

输出

"<span class="someColorClass">432,232,121</span>,678"
"221"

See this example on jsFiddle