Comma separate strings and numbers in JavaScript

I recently had to format large numbers using JavaScript and was really missing Rails’ number_with_delimiter function. Heres a simple version for JavaScript.

// Allow strings to number_to_currency style comma seperate
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, "$&,");
  });
}

// Convenience method for numbers
Number.prototype.commafy = function () {
  return String(this).commafy();
}

View Gist