score:2

This would be more concise if JavaScript RegExp had a backwards flag. Since it doesn't, we have to reverse the string, insert the punctuation, then reverse it back.

Parsing is simply replacing all non-numbers, \D, with nothing.

I am more familiar with using the period . as a decimal, and commas , as thousands separators, but it should be easy for you to invert this.

const numbers = [1, 12, 123, 1234, 12345, 123456, 1234567, 12345678, 123456789].map(String);

function format(number) {
  return number
    .split('').reverse().join('')
    .replace(/(\d{1,2})(\d{1,3})?(\d{1,3})?(\d{1,3})?/, '$1.$2,$3,$4')
    .split('').reverse().join('')
    .replace(/^,+/, '')
}

function parse(money) {
  return money.replace(/\D/g, '');
}

function log(n) {
  console.log(n);
}

numbers
  .map(format)
  .forEach(log);


Related Query

More Query from same tag