I’ve written a JavaScript function to add thousands separators (,) to numeric literals within an expression,
My current code works fine but breaks when the expression contains numbers already formatted with commas.
For example
This would work
formatExp("1000 + 10000") //output: "1,000 + 10,000"
This will not
formatExp("1,0000") //would result in "1,0,000"
I tried modify the regex to ignore already formatted number literals
const NUMBER_REGEX = /(?:d{1,3})(?:,?d{3})*/g;
Where the first part matches 1-3 digits
/(?:d{1,3})
And the second part matches zero or more occurrence of an optional comma followed by exactly 3 digits
(?:,?d{3})*/g;
Kindle is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.