I’m trying to write the regex that will format the number like 1231231.00
to 1,231,231.00
. I’ve written something like this:
let test = "1231231.00";
console.log(test.replace(/(d)(?=(d{3})+$)/g, "$1,"))
But I still have problem when I try to format 1231231.00
. Can anyone give me a hint?
2
Answers
If your goal is to add thousands grouping to a numerical output in a reliable and repeatable manner, try using
Intl.NumberFormat()
:The problem is in this:
Your regex is searching for a string of digits, followed by an end-of-string. This assumption breaks if you have a decimal point, because the digits are not immediately followed by the end-of-string.
Here is a quick fix:
I have loosened the check to be "end-of-string or period".
However, I share the above code primarily for academic/learning purposes.
In a production system I’d prefer to use a library for this (e.g.
Intl.NumberFormat
, as mentioned in another answer) rather than hacking something together myself with regex.