1

I have a simple question, I would like to replace dots to commas and commas to dots in a string, example:

var example1 = "10.499,99" // What I have
var result1 = "10,499.49" // What I need

var example2 = "99.999.999.999,99" // What I have
var result2 = "99,999,999,999.99" // What I need

I already tried to use this replace:

value.replace(/,/g, '.')

But it only changes all commas to dots.

Any idea ?

NewProgrammer
  • 442
  • 3
  • 16

4 Answers4

2

Use the variant of the replaceAll function that takes a function as the second parameter. Use it to replace all occurrences of either dot or comma. The function will choose to replace dots with commas and commas with dots.

function switchDotsAndCommas(s) {

  function switcher(match) {
    // Switch dot with comma and vice versa
    return (match == ',') ? '.' : ',';
  }

  // Replace all occurrences of either dot or comma.
  // Use function switcher to decide what to replace them with.
  return s.replaceAll(/\.|\,/g, switcher);
}


console.log(switchDotsAndCommas('10.499,99'));
console.log(switchDotsAndCommas('99,999,999,999.99'));
NineBerry
  • 26,306
  • 3
  • 62
  • 93
1

You can't do it at the same time. If you use replace function to change it from dot(.) -> comma(,) you will get your new string where a comma is replaced by a dot. But when you again try to do vice versa every comma will be replaced with a dot.

So what you can do is Replace the comma with a different string/symbol something like replace(/,/g , "__") then replace the dots with the same expression you are using above replace(/\./g, ',') and that replace those new string/(__) in our example to dot(.) replace(/__/g, '.')

var example2 = "99.999.999.999,99" example2.replace(/,/g , "__").replace(/\./g, ',').replace(/__/g, '.') //output : '99,999,999,999.99'

Happy Coding

Dharman
  • 30,962
  • 25
  • 85
  • 135
-1

Use

value.replace(".", ",");
JulesUK
  • 359
  • 2
  • 11
-1
value.replace(".",",")
Dharman
  • 30,962
  • 25
  • 85
  • 135
Ashwini
  • 17
  • 2
  • This is the same as [this answer](https://stackoverflow.com/a/71603644/1364007) which was posted about an hour earlier. – Wai Ha Lee Mar 24 '22 at 17:49