var format = function(n){return n.toString().replace(/(\d+)(\d{3})/, '$1,$2');}; alert( [format(123), format(1234), format(12345), format(12346), format(123467), format(1234678)].join('\n') )