Regex to Add Thousand Separators to Numbers
Regex to insert thousand separators (commas, dots, or spaces) into numeric strings. Handles integers, decimals, and negative numbers using lookahead assertions.
Detailed Explanation
Add Thousand Separators with Regex
For display purposes, large numbers are easier to read with separators every three digits. The classic regex uses a lookahead to insert a comma after every digit that has a multiple-of-three count of digits remaining.
Comma Separator
str.replace(/\B(?=(\d{3})+(?!\d))/g, ",")
Breakdown:
\Bmatches a position that is not a word boundary (so the leading edge does not get a comma)(?=(\d{3})+(?!\d))looks ahead and ensures the remaining digits are an exact multiple of three
Tested Examples
| Input | Output |
|---|---|
"1234" |
"1,234" |
"1234567" |
"1,234,567" |
"123" |
"123" |
"1234.56" |
"1,234.56" (only integer part is touched) |
"-9876543" |
"-9,876,543" |
Explicit Integer-Part Targeting
When the number has a decimal portion, restrict the replace to the integer part:
function format(n) {
const [int, dec] = String(n).split(".");
return int.replace(/\B(?=(\d{3})+(?!\d))/g, ",") + (dec ? "." + dec : "");
}
Different Separators
European convention uses dots for thousands and commas for decimals:
str.replace(/\B(?=(\d{3})+(?!\d))/g, ".")
For Indian numbering (12,34,567), the grouping is 3-2-2:
str.replace(/(\d)(?=(\d\d)+\d$)/g, "$1,")
12345678 becomes 1,23,45,678.
Practical Recommendation
For locale-aware formatting, use Intl.NumberFormat:
new Intl.NumberFormat("en-US").format(1234567.89) // "1,234,567.89"
new Intl.NumberFormat("de-DE").format(1234567.89) // "1.234.567,89"
The regex approach is useful when you need to format numbers embedded in larger strings (e.g., log lines or templates) without parsing them as numbers first.
Use Case
Formatting numbers inside log messages or HTML templates without converting to and from Number, or adding separators in a CSV export pipeline that must preserve original numeric strings.