Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
23
rated 0 times [  26] [ 3]  / answers: 1 / hits: 28293  / 9 Years ago, sat, december 12, 2015, 12:00: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


More From » regex

 Answers
32

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





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.


[#64091] Wednesday, December 9, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
zaynerogerb

Total Points: 454
Total Questions: 109
Total Answers: 97

Location: Comoros
Member since Tue, Mar 14, 2023
1 Year ago
zaynerogerb questions
;