[フレーム]
Last Updated: February 25, 2016
·
10.01K
· 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();

AltStyle によって変換されたページ (->オリジナル) /