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"
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"
2 Answers
Reset to default 27Use 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()
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.
So, when first ,
from the string is matched
m = ',';
And in the function return m === ',' ? '.' : ',';
is equivalent as
if (m === ',') {
return '.';
} else {
return ',';
}
So, basically this is replacing ,
by .
and .
by ,
in the string.
Nothing wrong with Tushar's approach, but here's another idea:
myString
.replace(/,/g , "__COMMA__") // Replace `,` by some unique string
.replace(/\./g, ',') // Replace `.` by `,`
.replace(/__COMMA__/g, '.'); // Replace the string by `.`
.
(or comma) will make the other replace revert the first replace. – Tushar Commented Dec 12, 2015 at 8:54