我有一个字符串"1,23,45,448.00",我想用小数点替换所有逗号,用逗号替换所有小数点.
我要求的输出是"1.23.45.448,00"
我试图取代,通过.如下:
var mystring = "1,23,45,448.00"
alert(mystring.replace(/,/g , "."));
Run Code Online (Sandbox Code Playgroud)
但是,在那之后,如果我尝试.用,它替换它也会替换第一个被替换.为,导致输出为"1,23,45,448,00"
Tus*_*har 21
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);Run Code Online (Sandbox Code Playgroud)
正则表达式:正则表达式[,.]将匹配逗号或小数点中的任何一个.
String#replace()使用函数回调将获得匹配的参数(m),它是,或者.和函数返回的值用于替换匹配.
所以,当第一个,字符串匹配时
m = ',';
Run Code Online (Sandbox Code Playgroud)
并在功能 return m === ',' ? '.' : ',';
相当于
if (m === ',') {
return '.';
} else {
return ',';
}
Run Code Online (Sandbox Code Playgroud)
所以,基本上,这是更换,由.并且.通过,了的字符串中.
小智 5
杜莎尔(Tushar)的做法没错,但这是另一个想法:
myString
.replace(/,/g , "__COMMA__") // Replace `,` by some unique string
.replace(/\./g, ',') // Replace `.` by `,`
.replace(/__COMMA__/g, '.'); // Replace the string by `.`
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17535 次 |
| 最近记录: |