替换,(逗号)by。(点)和。(点)by,(逗号) [英] Replace ,(comma) by .(dot) and .(dot) by ,(comma)

查看:214
本文介绍了替换,(逗号)by。(点)和。(点)by,(逗号)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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"

我试图替换如下:

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

但是,之后,如果我尝试更换 by 它还替换了第一个被替换的导致输出为1,23,45,448,00

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"

推荐答案

使用替换并使用回调函数替换 。 / code>和。函数返回的值将用于替换匹配的值。

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() ,函数为ca llback将获得匹配参数( m ),这是并且从函数返回的值用于替换匹配。

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.

因此,当第一个时,

m = ',';

在函数中返回m ===','? '。':',';

相当于

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

所以,基本上这是替换 by by in字符串。

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

这篇关于替换,(逗号)by。(点)和。(点)by,(逗号)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆