将,(逗号)替换为.(点)和.(点)by,(逗号)

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

本文关键字:逗号 by 替换      更新时间:2023-09-26

我有一个字符串"1,23,45,448.00",我想用小数点替换所有逗号,用逗号替换所有小数点。

我需要的输出是"1.23.45.448,00"

我尝试用.替换,,如下所示:

var mystring = "1,23,45,448.00"
alert(mystring.replace(/,/g , "."));

但是,在那之后,如果我试图用,替换.,它也会用,替换第一个替换的.,从而将输出作为"1,23,45,448,00"

使用带有回调函数的replace,该函数将用.替换,,用,替换.。函数返回的值将用于替换匹配的值。

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:正则表达式[,.]将匹配逗号或小数点中的任何一个。

带有函数回调的String#replace()将获得匹配作为参数(m),该参数是,.,并且从函数返回的值用于替换匹配。

因此,当字符串中的第一个,与匹配时

m = ',';

在函数return m === ',' ? '.' : ',';

相当于

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

所以,基本上这是用.替换,,用,替换.

Tushar的方法没有错,但这里有另一个想法:

myString
  .replace(/,/g , "__COMMA__") // Replace `,` by some unique string
  .replace(/'./g, ',')         // Replace `.` by `,`
  .replace(/__COMMA__/g, '.'); // Replace the string by `.`