0
var price = "19,99 $"
price.replace(/[^0-9,.]/g, '').replace(",",".");
console.log(price)

output
19.99
  • but I need to replace two replace operations with a single replace! is it possible?
Aman Anku
  • 27
  • 7
  • What you've shown as the output of the above isn't, because you never assign back to `price`. `replace` *returns* the result, it doesn't modify the string in place. (Strings are immutable.) – T.J. Crowder Mar 12 '21 at 09:02

3 Answers3

1

It's possible, but it may not be worthwhile. You have to pass a function as the second argument:

var price = "19,99 $";
price = price.replace(/[^0-9.]/g, m => m === "," ? "." : "");
console.log(price);

I removed , from the negated character class, then in the callback checked to see if the match was a , and returned "." if so, "" if not. Also note assigning the result back to price (your original wasn't, it was throwing away the result).

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1

You could get all digits and join with dot.

var price = "19,99 $"
price = price.match(/\d+/g).join('.');

console.log(price);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

You can replace anything that is not 0-9 and , with " ".After that split the string with comma as separator and join with dot.

const price = "19,99 $"
const result = price.replace(/[^0-9,]/g,"").split(",").join(".");

console.log(result);