Best way to remove thousand separators from string amount using a regex

user2571510 picture user2571510 · Nov 24, 2014 · Viewed 13.4k times · Source

I have variables that contain amounts and would like to remove the (US) thousand separators but also have to cover the scenario that there may be non-US formatted amounts where the comma is used for the decimals instead of for the thousands where I don't want to replace the comma.

Examples:

  • 1,234,567.00 needs to become 1234567.00
  • 1,234.00 needs to become 1234.00
    but
  • 1.234.567,00 needs to remain unchanged as not US format (i.e. comma here is used for decimals)
  • 1.234,00 needs to remain unchanged as not US format (i.e. comma here is used for decimals)

I was thinking of using the following but wasn't sure about it as I am pretty new to Regex:

myVar.replace(/(\d+),(?=\d{3}(\D|$))/g, "$1");

What is best solution here? Note: I just need to cover normal amounts like the above examples, no special cases like letter / number combinations or things like 1,2,3 etc.

Answer

sp00m picture sp00m · Nov 24, 2014

This one may suit your needs:

,(?=[\d,]*\.\d{2}\b)

Regular expression visualization

Debuggex Demo