Samuel Miller
Fractured Obelisk

Fractured Obelisk

Assume sufficiently advanced Regex is copied

Assume sufficiently advanced Regex is copied

...and is magic

Samuel Miller's photo
Samuel Miller
·Jan 6, 2022·

1 min read

Subscribe to my newsletter and never miss my upcoming articles

I came across a snippet of javascript code today to add commas to a number.

let commaNum = numStr.replace(/\B(?=(\d{3})+(?!\d))/g, ",");

As soon as I saw it, I suspected someone had copied it from somewhere else. After some digging I found I was right and it had been copied multiple times for years. I can find it in StackOverflow and blogs which leads me to my Law of Regex...

Assume sufficiently advanced Regex is copied

which is fine but please also link to where the regex was copied. Eventually someone will track down a bug to the regex like I did with this regex. If you have more than three decimal places...


"1234.1234".replace(/\B(?=(\d{3})+(?!\d))/g, ",");
//'1,234.1,234'

The regex(and bug) had been copied around and that bug had been commented on but if there was a reference in a comment, it could have saved me little extra time and potentially more Devs in the future also.

PS. Modern browsers handle this a better way with internationalization now

 
Share this