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

前端 未结 5 1889
孤城傲影
孤城傲影 2021-01-12 17:59

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 wh

相关标签:
5条回答
  • 2021-01-12 18:26
    if (string.match(/\.\d{2}$/) {
        string = string.replace(',', '');
    }
    

    or

    string.replace(/,(?=.*\.\d+)/g, '');
    
    0 讨论(0)
  • 2021-01-12 18:28

    This one may suit your needs:

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

    Regular expression visualization

    Debuggex Demo

    0 讨论(0)
  • 2021-01-12 18:34

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

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

    0 讨论(0)
  • 2021-01-12 18:34

    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'
    
    0 讨论(0)
  • 2021-01-12 18:42

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

    http://regexr.com/39v2m

    0 讨论(0)
提交回复
热议问题