OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

How to format a number literal within a JavaScript expression [closed]

  • Thread starter Thread starter Kindle
  • Start date Start date
K

Kindle

Guest
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

Code:
formatExp("1000 + 10000"); //output: "1,000 + 10,000"

This will not

Code:
formatExp("1,0000"); //output: "1,0,000"

My code

Code:
const THOUSANDS_SEPARATOR_REGEX = /\B(?=(\d{3})+(?!\d))/g;  // Regular expression to match every third digit from the end

function formatExp(expression) {
  // Replace numbers matched by NUMBER_REGEX in the expression
  return expression.replace(NUMBER_REGEX, function(match) {
    return match.replace(THOUSANDS_SEPARATOR_REGEX, ",");
  });
}```

<p>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</p>
<p><strong>This would work</strong></p>
<pre><code>formatExp("1000 + 10000"); //output: "1,000 + 10,000"
</code></pre>
<p><strong>This will not</strong></p>
<pre><code>formatExp("1,0000"); //output: "1,0,000"
</code></pre>
<p>My code</p>
<pre><code>const THOUSANDS_SEPARATOR_REGEX = /\B(?=(\d{3})+(?!\d))/g; // Regular expression to match every third digit from the end

function formatExp(expression) {
// Replace numbers matched by NUMBER_REGEX in the expression
return expression.replace(NUMBER_REGEX, function(match) {
return match.replace(THOUSANDS_SEPARATOR_REGEX, ",");
});
}```
</code></pre>
 
Top