2024-09-09 web, development, javascript
How to Add Commas to Numbers at the Thousands Place
By O. Wolfson
Add commas to numbers at the thousands place with regex using this clever regular expression: \B(?=(\d{3})+(?!\d))/g
This solution was found on Stack Overflow, here.
The code below is Javascript. It will transform a string using the replace method, based on the regex that we’ve added as an argument.
See the output below.
To understand how this expression works, you should have a basic understanding of regular expressions, given that – let’s it break down.
The beginning:
Note that the regex pattern \b
will match for word boundaries. For example, if we wanted to add quotes to a word we might search for the word boundary position and replace with quotes, like this: replace(/\b/g, ‘”‘)
. This expression will add quotes to the beginning and end of a word.
Generally, using the capitalized variation of a pattern will match the opposite of the lower case version. /B
matches for characters that are NOT at word boundaries. This is important because our goal is to add commas at thousands places. We do not want to add commas at the beginning or end of a number, only inside at the thousands breaks.
The code below will add commas at each character position that is not at a word boundary. The g
flag is added to the regex so that commas are added to every match, not just the first match.
Back to our expression
We use the ?=(\d{3})+
pattern to specify that we are searching for one or more groups of three digits. ?=
is a “positive lookahead” flag. A positive lookahead is an assertion that specifies that we want to match for something that is followed by something specific. In this case, we want to match for a non-word-boundary position (where we can add our comma) followed by three digits. \d
matches for numeric characters. {x}
matches a sequence of a specific length, in our case 3.
Pictured above is a test of the regular expression at https://regex101.com/. Note how every position that is not a word boundary, and is followed by three digits is matched. The problem is, if our number is bigger than 1000, the match will repeat for every other position that is followed by three digits. Actually we want to match only positions for commas at ‘thousands places’, at intervals of three digits.
The (?!\d))
pattern checks that the groups matched not followed by more digits. This ensures that the last three digits in the number become a group, and other groups of three are matched similarly.