angularregextypescriptsonarqube

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:

 // 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"