Skip to content Skip to sidebar Skip to footer

Best Way To Remove Thousand Separators From String Amount Using A Regex

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

Solution 1:

This one may suit your needs:

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

Regular expression visualization

Debuggex Demo

Solution 2:

if (string.match(/\.\d{2}$/) {
    string = string.replace(',', '');
}

or

string.replace(/,(?=.*\.\d+)/g, '');

Solution 3:

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'

Solution 5:

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

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

Post a Comment for "Best Way To Remove Thousand Separators From String Amount Using A Regex"