format number

Benchmark created on


Setup

const priceString = '12345';
  const sepparator = ' ';
  const digitCount = 3;
  let result;

Test runner

Ready to run.

Testing in
TestOps/sec
decorateByReplace
result = priceString
  .split('')
  .reverse()
  .join('')
  .replace(new RegExp(`(.{${digitCount}})`, 'g'), '$1' + sepparator)
  .split('')
  .reverse()
  .join('');
ready
decorateByLoop
let priceArray = [];
for (let i = priceString.length; i > 0; i -= digitCount) {
  priceArray.push(priceString.slice(Math.max(i - digitCount, 0), i));
}

result = priceArray.reverse().join(sepparator);
ready
decorateByRegExp
const regexp = new RegExp(`(^.{1,${digitCount - 1}})|(.{1,${digitCount}})`, 'g');
const matches = priceString.match(regexp);

result = matches ? matches.join(sepparator) : '';
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.