Javascript 将 ,(comma) 替换为 .(dot) 并将 .(dot) 替换为 ,(comma)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34238005/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:04:45  来源:igfitidea点击:

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

javascriptregex

提问by manoj

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.

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

My required output is "1.23.45.448,00"

我需要的输出是“1.23.45.448,00”

I've tried to replace ,by .as follow:

我试图取代,通过.如下:

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

But, after that, if I try to replace .by ,it also replaces the first replaced .by ,resulting in giving the output as "1,23,45,448,00"

但是,在那之后,如果我尝试替换它.,它也会替换第一个替换.,导致输出为"1,23,45,448,00"

回答by Tushar

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

replace与将替换,by..by 的回调函数一起使用,。函数的返回值将用于替换匹配的值。

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.

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

So, when first ,from the string is matched

所以,当第一个,从字符串匹配时

m = ',';

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

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

is equivalent as

等价于

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

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

所以,基本上这是在字符串中替换,by..by ,

回答by manoj

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

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

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