Emmanuel Akinfulubi

JavaScriptRegular expressions

Add commas to a number with regex in JavaScript

Intermediate · 3 min read

1234567 is hard to read. 1,234,567 is easy. Prices, bank balances, view counts and reports all put commas between groups of three digits. The exercise gives three examples to match: 1000 becomes '1,000', 10000.23 becomes '10,000.23', and 100000 becomes '100,000'.

In this tutorial you will do it with a single replace and a clever regular expression, then learn why real code should use Intl.NumberFormat instead. The regex uses lookaheads, which match a position between characters rather than the characters themselves. You need to know replace, split and \d. Lookaheads are explained from zero.

Where do the commas go?

Look at 1234567 from the right. A comma goes at every position that has a multiple of three digits after it:

Positions

1 , 2 3 4 , 5 6 7
  ^ six digits after this gap
          ^ three digits after this gap

So the question for each gap between two digits is: "are the digits to my right a multiple of three?" If yes, put a comma there.

Matching a position, not a character

A lookahead, written (?=...), checks what comes next without using it up. It matches the gap before the text, not the text itself. Replacing a gap inserts something without removing anything:

JavaScript

console.log('ab'.replace(/(?=b)/, '-')); // 'a-b'

(?=b) matched the empty gap in front of b, and replace put - there.

Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.

21 Thousands separators

fair

Print an integer with commas between thousands. The test data: 1000 gives "1,000", 10000.23 gives "10,000.23", 100000 gives "100,000".

Stuck? Three hints, smallest first
  1. 1. Only the integer part gets separators. Split on the dot first.
  2. 2. \B(?=(\d{3})+(?!\d)) finds each position with a multiple of three digits after it.
  3. 3. Intl.NumberFormat does this properly, and you must pass a locale.

Step 1: groups of three to the right

(\d{3})+ means "one or more groups of exactly three digits". Put it in a lookahead with the g flag, so every matching gap gets a comma:

JavaScript

console.log('100000'.replace(/(?=(\d{3})+)/g, ',')); // ',1,0,0,000'

Far too many commas. Any gap with at least three digits after it matches, because the lookahead doesn't say where the digits must stop.

Step 2: stop at the end of the number

(?!\d) is a negative lookahead: "no digit comes next". Putting it after the groups means the groups of three must run right up to the end:

JavaScript

console.log('100000'.replace(/(?=(\d{3})+(?!\d))/g, ',')); // ',100,000'

Almost right. There's an extra comma at the very start, because the gap before the first 1 also has six digits after it.

Step 3: no comma at the start

\B means "not a word boundary". A word boundary is the edge where a word starts or ends, such as the start of the string before 1. Gaps between two digits are not boundaries, so \B allows those and refuses the start:

Step 3

const group = (digits) => digits.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
console.log(group('1234567')); // '1,234,567'
console.log(group('100000'));  // '100,000'
console.log(group('999'));     // '999'
console.log(group('-1234'));   // '-1,234'

A minus sign stays put. The gap between - and 1 is a word boundary, so no comma lands there.

Step 4: leave the decimals alone

Try a number with a fraction:

JavaScript

const group = (digits) => digits.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
console.log(group('1234.5678')); // '1,234.5,678'

The digits after the dot got grouped too, which is wrong. Split on the dot first, group only the whole part, then join them back:

Step 4

function thousandsSeparators(value) {
  const [whole, fraction] = String(value).split('.');
  const grouped = whole.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
  return fraction === undefined ? grouped : `${grouped}.${fraction}`;
}
console.log(thousandsSeparators(1000));       // '1,000'
console.log(thousandsSeparators(10000.23));   // '10,000.23'
console.log(thousandsSeparators(100000));     // '100,000'
console.log(thousandsSeparators(1234.56789)); // '1,234.56789'

All three examples from the exercise now match. When there is no dot, fraction is undefined, and the whole part is returned alone.

Step 5: what real code should use

Intl.NumberFormat is built into JavaScript and knows how each country writes numbers. Always pass a locale, or the result depends on the computer it runs on:

Step 5

console.log(new Intl.NumberFormat('en-NG').format(1234567)); // '1,234,567'
console.log(new Intl.NumberFormat('de-DE').format(1234567)); // '1.234.567'
console.log(new Intl.NumberFormat('en-IN').format(1234567)); // '12,34,567'

German uses dots between thousands. Indian grouping isn't in threes at all after the first group. The regex can only do one style, so it's a good learning exercise, and Intl is what you ship.

The full solution

The panel runs the regex version and Intl side by side on the same numbers, then prints one value in three locales. Press Run and compare the columns.

The answer

/* \B      not at a word boundary, so no comma is placed at the very start
   (?=...) a lookahead: the position is only matched, nothing is consumed
   (\d{3})+ one or more groups of exactly three digits
   (?!\d)  and no fourth digit after them
   Together: every position with a multiple of three digits to its right.     */
function thousandsSeparators(value) {
  const [whole, fraction] = String(value).split('.');
  const grouped = whole.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
  return fraction === undefined ? grouped : `${grouped}.${fraction}`;
}

// What to use in real code. The locale is NOT optional: without it the output
// depends on the machine, and the same code gives different answers elsewhere.
const formatted = (value) => new Intl.NumberFormat('en-NG').format(value);

const cases = [1000, 10000.23, 100000, 999, 1000000, 0, 12, -1234567, 1234.5];

for (const n of cases) {
  console.log(String(n).padEnd(12), 'regex:', thousandsSeparators(n).padEnd(14), 'Intl:', formatted(n));
}
console.log('--- the same value in three locales ---');
for (const locale of ['en-NG', 'de-DE', 'en-IN']) {
  console.log(locale.padEnd(6), new Intl.NumberFormat(locale).format(1234567.89));
}

Output


      
20 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 20 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

20 checks

test("the first case", thousandsSeparators(1000), '1,000');
test("the second case", thousandsSeparators(10000.23), '10,000.23');
test("the third case", thousandsSeparators(100000), '100,000');
test('three digits get no comma', thousandsSeparators(999), '999');
test('a million gets two', thousandsSeparators(1000000), '1,000,000');
test('zero is unchanged', thousandsSeparators(0), '0');
test('two digits are unchanged', thousandsSeparators(12), '12');
test('a negative number keeps its sign', thousandsSeparators(-1234567), '-1,234,567');
test('the fraction is never grouped', thousandsSeparators(1234.5), '1,234.5');
test('a long fraction is left alone', thousandsSeparators(1234.56789), '1,234.56789');
test('exactly four digits get one comma', thousandsSeparators(1234), '1,234');
test('the boundary at six digits', thousandsSeparators(123456), '123,456');
test('and at seven', thousandsSeparators(1234567), '1,234,567');
test('it agrees with Intl on integers', cases.filter(Number.isInteger).every((n) => thousandsSeparators(n) === formatted(n)), true);
test('Intl formats a million the same way', formatted(1000000), '1,000,000');
test('German uses dots for thousands', new Intl.NumberFormat('de-DE').format(1234567), '1.234.567');
test('and a comma for the decimal', new Intl.NumberFormat('de-DE').format(1234.5), '1.234,5');
test('Indian grouping is not in threes', new Intl.NumberFormat('en-IN').format(1234567), '12,34,567');
test('which the regex cannot do', thousandsSeparators(1234567) === new Intl.NumberFormat('en-IN').format(1234567), false);
test('naira formatting, with the currency', new Intl.NumberFormat('en-NG', { style: 'currency', currency: 'NGN' }).format(4500).replace(/\u00a0/g, ' '), '\u20a64,500.00');

B(?=(d{3})+(?!d)) is worth taking apart. (?=…) is a lookahead, so it matches a position and consumes nothing — that is what lets replace insert a comma without removing a digit. (d{3})+ requires a whole number of three-digit groups to the right, (?!d) stops there being a fourth digit, and B prevents a comma at the very start of the string. Splitting the fraction off first is necessary because those rules would otherwise group the digits after the dot too.

Then the honest conclusion: use Intl.NumberFormat. The assertions show why the regex cannot be right in general — German writes 1.234.567, and Indian grouping is 12,34,567, which is not in threes at all. And always pass a locale. Without one, Intl uses the machine's, so the same code produces different output on your laptop and on a server, and any test asserting the result becomes a coin flip.

Common mistakes

  • Grouping the decimals. Split on the dot first, or 1234.5678 turns into 1,234.5,678.
  • Leaving out \B. You get a comma at the start of numbers with 3, 6 or 9 digits, like ',100,000'.
  • Calling Intl.NumberFormat() with no locale. The output then depends on the machine, so your tests can pass on one computer and fail on another.

Try it yourself

  1. Use a dot instead of a comma as the separator, the way German writes numbers.
  2. Write formatNaira(n) with new Intl.NumberFormat('en-NG', { style: 'currency', currency: 'NGN' }).
  3. Write removeSeparators('1,234,567') that gives back the number 1234567. (Hint: replace(/,/g, ''), then Number.)

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.