问题
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.
回答1:
This one may suit your needs:
,(?=[\d,]*\.\d{2}\b)
Debuggex Demo
回答2:
Replace /,(?=\d*[\.,])/g
with empty string?
http://regexr.com/39v2m
回答3:
if (string.match(/\.\d{2}$/) {
string = string.replace(',', '');
}
or
string.replace(/,(?=.*\.\d+)/g, '');
回答4:
myVar = myVar.replace(/([.,])(\d\d\d\D|\d\d\d$)/g,'$2');
Removes the period . or comma , when used as a thousand separator.
来源:https://stackoverflow.com/questions/27105755/best-way-to-remove-thousand-separators-from-string-amount-using-a-regex