Last Updated: February 25, 2016
·
9.82K
· derrylwc

Easily add commas to strings in JavaScript

I came across this regex sometime ago which adds commas to numbers in JavaScript (e.g. 1040245 -> 1,040,245).

When I'm working on an application that involves displaying lots of data, I'll usually include this in my code:

String.prototype.commafy = function () {
    return this.replace(/(^|[^\w.])(\d{4,})/g, function($0, $1, $2) {
        return $1 + $2.replace(/\d(?=(?:\d\d\d)+(?!\d))/g, "$&,");
    });
};

If you're working with non-Strings, you can add this function as well:

Number.prototype.commafy = function () {
    return String(this).commafy();
};

Calling it thereafter is child's play:

var foo = "1234567"
var foobar = foo.commafy()

Or, more realistically:

var clicks = item[totalClicks].commafy();