I saw this beautiful script to add thousands separator to js numbers:
function thousandSeparator(n, sep)
{
var sRegExp = new RegExp(\'(-?[0-9]+)([0-9]{3
Here is an ugly script to contrast your beautiful script.
10000000.0001 .toString().split('').reverse().join('')
.replace(/(\d{3}(?!.*\.|$))/g, '$1,').split('').reverse().join('')
Since we don't have lookbehinds, we can cheat by reversing the string and using lookaheads instead.
Here it is again in a more palatable form.
function thousandSeparator(n, sep) {
function reverse(text) {
return text.split('').reverse().join('');
}
var rx = /(\d{3}(?!.*\.|$))/g;
if (!sep) {
sep = ',';
}
return reverse(reverse(n.toString()).replace(rx, '$1' + sep));
}