In order to add commas to a number string I'm using the following:
someNum.toString().replace(/\B(?=(?:\d{3})+(?!\d))/g, ",")
I need to do one extra thing. I need to wrap开发者_StackOverflow社区 everything to the left of the comma (all numbers representing thousands or above in a span
tag in order to color those numbers.
So if someNum
is 42221
the output whould be <span class="someColorClass">42</span>,221
and if someNum
was 221
the output would be 221
.
Thanks!
I don't know if its the most efficient way, but this works:
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
Assuming you never go into the millions, after your initial replace you can just do:
someNum = someNum.replace(/(\d*)(,\d{3})/g, '<span class="someColorClass">$1</span>$2');
With two regular expressions:
var someNum = 12345;
var commaNum = someNum.toString().replace(/\B(?=(?:\d{3})+(?!\d))/g, ",").replace(/^(\d+),/,"<span>$1</span>,");
alert(commaNum);
It would fail highlighting the thousands if it is in the millions.
Example
If the number can be greater than 99,999 than you can use this regular expression that matches anything. It will include the commas inside of the match.
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
Different approach, checking the string length...
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);
Output
"<span class="someColorClass">432,232,121</span>,678"
"221"
See this example on jsFiddle
精彩评论