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

前端 未结 5 1901
孤城傲影
孤城傲影 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: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'
    

提交回复
热议问题