How to replace dots to commas and commas to dots in js

Viewed 564

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 ?

4 Answers

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

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

Related