JSFiddle - React, Tailwind, and code Playground
JavaScript
console.time('regex')
for(var i = 1000; i < 1000000; i++) {
i.toString().replace( /\B(?=(?:\d{3})+$)/g, ',' )
}
console.timeEnd('regex')
console.time('nativeSlice')
for(var i = 1000; i < 1000000; i++) {
nativeSlice(i)
}
console.timeEnd('nativeSlice')
console.time('mathPower')
for(var i = 1000; i < 1000000; i++) {
mathPower(i)
}
console.timeEnd('mathPower')
function nativeSlice(i){
var s = i.toString();
var o = [];
var l = s.length;
var off = l % 3;
var groups = Math.floor(l / 3);
var x;
if (off) {
o.push(s.slice(0, off));
}
for (x = 0; x < groups; x++) {
o.push(s.slice(off, off += 3));
}
var result = o.join(",");
return result
}
function mathPower (num){
if (num < 999)
return num;
return mathPower(~~(num / 1000)) + "'"
+ ("00"+(~~(num % 1000))).substr(-3,3);
}