17

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"

Tushar
  • 85,780
  • 21
  • 159
  • 179
Manoj
  • 289
  • 1
  • 2
  • 11
  • So? What's isn't working for you? – Adam Azad Dec 12 '15 at 08:50
  • @AdamAzad When first replaced `.`(_or comma_) will make the other replace revert the first replace. – Tushar Dec 12 '15 at 08:54
  • 1
    @Tushar, these details should be present in the question, rather than in a comment. Good quality questions should describe the issue well enough without the need to add **essential** to the problem details in comments. A good description flow is to say **1) what I want to happen** then **2) what I am doing** and finally **3) what actually happens** – Ivaylo Slavov Dec 12 '15 at 08:58
  • 1
    @IvayloSlavov You're right, as this is first question of OP, the quality of question is _low_, edited to add more details. :) – Tushar Dec 12 '15 at 09:00
  • 1
    @Tushar, that is now way better. Glad to see quality improvement advices taken seriously :) – Ivaylo Slavov Dec 12 '15 at 09:01
  • If JS had hashes and interpolated variables at runtime, you could just put the replacement as `{hash[$1]}`, where `hash["."] = ","` and `hash[","] = "."` –  Dec 13 '15 at 02:43

2 Answers2

26

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.

rafaelncarvalho
  • 729
  • 7
  • 26
Tushar
  • 85,780
  • 21
  • 159
  • 179
5

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