代替 ,/逗号/ 在 ./观点/ 和 ./观点/ 在 ,/逗号/

我有一个名叫的字符串
"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:

regex
[,.]

它将对应于任何逗号或十进制半区。

https://developer.mozilla.org/ ... place
使用回调,该函数将被恰逢参数/
m

/, 这就是
,

, 或者
.

, 该功能返回的值用于取代巧合。

所以当第一个时
,

从字符串中将进行比较


m = ',';


在功能中
return m === ',' ? '.' : ',';


相当于如何


if /m === ','/ {
return '.';
} else {
return ',';
}


因此,主要是这种替代品
,


.


.


,

排队。

奔跑吧少年

赞同来自:

托斯卡尔的方法没有什么不好的,但这是另一个想法:


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

要回复问题请先登录注册