Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Format thousand separator properly without regex

In my Angular TypeScript code I have a function for formatting my value in this model:

1234 -> 1 234,000

First part of my function use regex like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 // delete 0 in string start and make 3 digits packets
    cleanedValue = cleanedValue.replace(/^0+(?=\d)/, '').replace(/\B(?=(\d{3})+(?!\d))/g, ' ');

It’s ok but Sonar give me a:

Make sure the regex used here, which is vulnerable to super-linear runtime due to backtracking, cannot lead to denial of service.

How can I do this without regex or without Sonar tell me this warning. Is this warning really positive?

>Solution :

No need for a regular expression in modern JS.

You can use the French (Switzerland) locale to format the number.

Note: Don’t forget to set the minimumFractionDigits to 3.

// Number formatter for French (Switzerland)
const frechSwissNumberFormatter = Intl.NumberFormat('fr-CH', {
  minimumFractionDigits: 3
});

// Convenience function
const formatNumber = (n) => frechSwissNumberFormatter.format(n)

// Format the number and print it
console.log(formatNumber(1234)); // "1 234,000"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading