Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
88
rated 0 times [  90] [ 2]  / answers: 1 / hits: 128701  / 15 Years ago, fri, february 12, 2010, 12:00:00

I need to display a formatted number on a web page using JavaScript. I want to format it so that there are commas in the right places. How would I do this with a regular expression? I've gotten as far as something like this:



myString = myString.replace(/^(d{3})*$/g, ${1},);


...and then realized this would be more complex than I think (and the regex above is not even close to what I need). I've done some searching and I'm having a hard time finding something that works for this.



Basically, I want these results:




  • 45 becomes 45

  • 3856 becomes 3,856

  • 398868483992 becomes 398,868,483,992



...you get the idea.


More From » regex

 Answers
5

This can be done in a single regex, no iteration required. If your browser supports ECMAScript 2018, you could simply use lookaround and just insert commas at the right places:



Search for (?<=d)(?=(ddd)+(?!d)) and replace all with ,



In older versions, JavaScript doesn't support lookbehind, so that doesn't work. Fortunately, we only need to change a little bit:



Search for (d)(?=(ddd)+(?!d)) and replace all with 1,



So, in JavaScript, that would look like:



result = subject.replace(/(d)(?=(ddd)+(?!d))/g, $1,);


Explanation: Assert that from the current position in the string onwards, it is possible to match digits in multiples of three, and that there is a digit left of the current position.



This will also work with decimals (123456.78) as long as there aren't too many digits to the right of the dot (otherwise you get 123,456.789,012).



You can also define it in a Number prototype, as follows:



Number.prototype.format = function(){
return this.toString().replace(/(d)(?=(d{3})+(?!d))/g, $1,);
};


And then using it like this:



var num = 1234;
alert(num.format());


Credit: Jeffrey Friedl, Mastering Regular Expressions, 3rd. edition, p. 66-67


[#97586] Wednesday, February 10, 2010, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
coby

Total Points: 27
Total Questions: 102
Total Answers: 97

Location: Honduras
Member since Wed, Jul 14, 2021
3 Years ago
;