Regex patterns/Numbers

Thousands separator positions

Matches nothing at all — just the positions where a comma belongs.

/\B(?=(\d{3})+(?!\d))/g
Open it in Rex

The problem

Find the positions in a run of digits where a thousands separator should be inserted.

How it reads

no word edgeahead: must be1\drepeatrepeatahead: must not be\d

Follow the line from left to right — every path you can trace is a string this pattern matches.

  1. \B(?=(\d{3})+(?!\d))In order:
  2. \BNot a word boundary
  3. (?=(\d{3})+(?!\d))Ahead of here there must be:
  4. (\d{3})+(?!\d)In order:
  5. (\d{3})+Repeated one or more times, as many as possible:
  6. (\d{3})Capture group 1:
  7. \d{3}A digit, exactly 3 times, as many as possible
  8. (?!\d)Ahead of here there must NOT be:
  9. \dA digit

Matches

  • 1234567
  • 1000
  • 10000

Does not match

  • 999
  • 42
  • abc

Where it bites

  • Every match is empty. This pattern exists purely to locate positions, which is why it is used with replace rather than with test.
  • The (?!\d) is what forces the groups of three to end at the last digit — without it, commas land in the wrong places.
  • \B stops a comma being inserted at the very start. Number.prototype.toLocaleString does all of this without a regex.

More numbers patterns