[Javascript] thousand separator

Shawn Milo milo at linuxmail.org
Thu Jun 3 06:56:06 CDT 2004


This regex was found in "Mastering Regular Expressions, 2nd Edition."

$pop =~ s/(?<=\d)(?=(\d\d\d)+$)/,/g;

I translated this to JS as:
someNum someNum.replace(/(?<=\d)+(?=(\d\d\d)+$)/g, ',');

For some reason, I get a regex error in IE and Mozilla, but I
found that removing the '<' (less than) character seems to
fix it.

The only problem I am running into is that it sometimes places
an extra comma at the beginning of the string.  When I run the
example below, they all come out fine except for the last one.

Further testing shows that the problem occurs for any number 
with a total length which is divisible by three.  Also, numbers
with decimals throw it off.

I'm going to work on an alternate solution.  In the meantime, does
anyone here have any good ideas on how to get the lookaround
working properly?

Shawn


      <script type="text/javascript">

         function addCommas(someNum){
            return someNum.replace(/(?=\d)+(?=(\d\d\d)+$)/g, ',');
            //someNum =
            //return 1;
         }

         alert(addCommas('6541684'));
         alert(addCommas('1000'));
         alert(addCommas('34562346346'));
         alert(addCommas('3456345634563456'));
         alert(addCommas('763773763567'));

      </script>



----- Original Message -----
From: "andy susanto" <andy78 at centrin.net.id>
Date: Thu, 3 Jun 2004 07:36:03 +0700
To: <javascript at LaTech.edu>
Subject: [Javascript] thousand separator 

> hai,
> 
> is there any script that can formating number with thousand separator ?, 
> 
> if not how to create that script ?
> 
> TIA,
> 
> andy
> _______________________________________________
> Javascript mailing list
> Javascript at LaTech.edu
> https://lists.LaTech.edu/mailman/listinfo/javascript




More information about the Javascript mailing list