6

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.

halfer
  • 19,824
  • 17
  • 99
  • 186
user2571510
  • 11,167
  • 39
  • 92
  • 138

6 Answers6

12

This one may suit your needs:

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

Regular expression visualization

Debuggex Demo

sp00m
  • 47,968
  • 31
  • 142
  • 252
5
if (string.match(/\.\d{2}$/) {
    string = string.replace(',', '');
}

or

string.replace(/,(?=.*\.\d+)/g, '');
hon2a
  • 7,006
  • 5
  • 41
  • 55
4

You can use replace() method to remove all the commas. They will be replaced with an empty string. I'm using reg exp with lookahead assertion to detect if a comma is followed by three digits, if so given comma will be removed.

string.replace(/,(?=\d{3})/g, '')

Examples:

'12,345,678.90'.replace(/,(?=\d{3})/g, '')
// '12345678.90'

'1,23,456.78'.replace(/,(?=\d{3})/g, '')
// '1,23456.78'

'$1,234.56'.replace(/,(?=\d{3})/g, '')
// '$1234.56'
user3812733
  • 165
  • 1
  • 9
2

Replace /,(?=\d*[\.,])/g with empty string?

http://regexr.com/39v2m

Sam Greenhalgh
  • 5,952
  • 21
  • 37
1

This code is worked for me and you can use it in set amount val for remove separators

t.replace(/,(?=\d{3})/g, '')
0

myVar = myVar.replace(/([.,])(\d\d\d\D|\d\d\d$)/g,'$2');

Removes the period . or comma , when used as a thousand separator.

JohnP2
  • 1,899
  • 19
  • 17