Last Updated: February 25, 2016
·
10.36K
· 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();

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Related Tags
#javascript
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside