Add comma to numbers every three digits

How can I format numbers using a comma separator every three digits using jQuery?

For example:

╔═══════════╦═════════════╗
║   Input   ║   Output    ║
╠═══════════╬═════════════╣
║       298 ║         298 ║
║      2984 ║       2,984 ║
║ 297312984 ║ 297,312,984 ║
╚═══════════╩═════════════╝

Solution 1:

@Paul Creasey had the simplest solution as the regex, but here it is as a simple jQuery plugin:

$.fn.digits = function(){ 
    return this.each(function(){ 
        $(this).text( $(this).text().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") ); 
    })
}

You could then use it like this:

$("span.numbers").digits();

Solution 2:

You could use Number.toLocaleString():

var number = 1557564534;
document.body.innerHTML = number.toLocaleString();
// 1,557,564,534

Solution 3:

Something like this if you're into regex, not sure of the exact syntax for the replace tho!

MyNumberAsString.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");