Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
466 views
in Technique[技术] by (71.8m points)

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

My required output is "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"

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...