Best way to remove thousand separators from string amount using a regex
Solution 1
This one may suit your needs:
,(?=[\d,]*\.\d{2}\b)
Solution 2
if (string.match(/\.\d{2}$/) {
string = string.replace(',', '');
}
or
string.replace(/,(?=.*\.\d+)/g, '');
Solution 3
Replace /,(?=\d*[\.,])/g
with empty string?
Solution 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'
user2571510
Updated on June 05, 2022Comments
-
user2571510 almost 2 years
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.
-
tomdemuyt over 9 yearsWill you always have 2 decimals? If not, then you will never know whether 1,234 is 1000 + 234 or 1 + 0.234
-
user2571510 over 9 yearsThanks - Yes, I will.
-
Julian almost 7 yearsfor me, this worked: ,(?=\d{3})
-
user2571510 over 9 yearsThanks for this - wouldnt I need to wrap this in / /g to cover all instances of thousand separators ?
-
user2571510 over 9 yearsThanks for this as well ! I am trying to understand what makes the most sense here for me.
-
albanx over 9 yearsthank you for the Debuggex Demo web site, never seen it before really great one the with the graph.
-
user2571510 over 9 yearsThanks - I would like to avoid using IF statements here.
-
sp00m over 9 years@user2571510 Yes, you'll have to enable the
global
flag:/theregex/g
. -
user2571510 over 9 yearsThanks, All - this works very well and I like the workflow image.
-
Mehdi Faraji over 2 yearsThis answer worked for me
-
eomeroff about 2 yearsThis works until you have Argentine Peso ARS '1.222,222'.replace(/,(?=\d{3})/g, '') evaluates to '1.222222'