简体   繁体   English

用。(点)替换(逗号)和用((逗号)替换。(点)

[英]Replace ,(comma) by .(dot) and .(dot) by ,(comma)

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"

Use replace with callback function which will replace , by . 使用replace用的回调函数将取代,通过. 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 . String#replace()与所述回调函数将得到匹配作为参数( m ),这是任一,. and the value that is returned from the function is used to replace the match. 从函数返回的值将用于替换匹配项。

So, when first , from the string is matched 因此,当first时,来自字符串的匹配

m = ',';

And in the function return m === ',' ? '.' : ','; 并在函数中return m === ',' ? '.' : ','; return m === ',' ? '.' : ',';

is equivalent as 等价于

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

So, basically this is replacing , by . 所以,基本上,这是替换,通过. and . . by , in the string. ,在字符串中。

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 `.`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM