Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...