Kyle Cureau
Kyle Cureau

Reputation: 19366

Wrap numbers to the left of a character

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 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!

Upvotes: 3

Views: 193

Answers (4)

BrunoLM
BrunoLM

Reputation: 100331

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

Upvotes: 0

epascarello
epascarello

Reputation: 207501

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

Upvotes: 0

Dan Manastireanu
Dan Manastireanu

Reputation: 1822

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

Upvotes: 4

mVChr
mVChr

Reputation: 50187

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');

Upvotes: 0

Related Questions