Replace ,(comma) by .(dot) and .(dot) by ,(comma)

前端 未结 2 1238
逝去的感伤
逝去的感伤 2020-12-06 16:45

I\'ve a string as \"1,23,45,448.00\" and I want to replace all commas by decimal point and all decimal points by comma.

My required output is \"1.23.45.

相关标签:
2条回答
  • 2020-12-06 17:01

    Use replace with callback function which will replace , by . and . by ,. The returned value from the function will be used to replace the matched value.

    var mystring = "1,23,45,448.00";
    
    mystring = mystring.replace(/[,.]/g, function (m) {
        // m is the match found in the string
        // If `,` is matched return `.`, if `.` matched return `,`
        return m === ',' ? '.' : ',';
    });
    
    //ES6
    mystring = mystring.replace(/[,.]/g, m => (m === ',' ? '.' : ','))
    
    console.log(mystring);
    document.write(mystring);

    Regex: The regex [,.] will match any one of the comma or decimal point.

    String#replace() with the function callback will get the match as parameter(m) which is either , or . and the value that is returned from the function is used to replace the match.

    So, when first , from the string is matched

    m = ',';
    

    And in the function return m === ',' ? '.' : ',';

    is equivalent as

    if (m === ',') {
        return '.';
    } else {
        return ',';
    }
    

    So, basically this is replacing , by . and . by , in the string.

    0 讨论(0)
  • 2020-12-06 17:23

    Nothing wrong with Tushar's approach, but here's another idea:

    myString
      .replace(/,/g , "__COMMA__") // Replace `,` by some unique string
      .replace(/\./g, ',')         // Replace `.` by `,`
      .replace(/__COMMA__/g, '.'); // Replace the string by `.`
    
    0 讨论(0)
提交回复
热议问题