Regex patterns/Numbers
Thousands separator positions
Matches nothing at all — just the positions where a comma belongs.
/\B(?=(\d{3})+(?!\d))/gThe problem
Find the positions in a run of digits where a thousands separator should be inserted.
How it reads
Follow the line from left to right — every path you can trace is a string this pattern matches.
\B(?=(\d{3})+(?!\d))In order:\BNot a word boundary(?=(\d{3})+(?!\d))Ahead of here there must be:(\d{3})+(?!\d)In order:(\d{3})+Repeated one or more times, as many as possible:(\d{3})Capture group 1:\d{3}A digit, exactly 3 times, as many as possible(?!\d)Ahead of here there must NOT be:\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.