javascriptreactjstypescriptreplaceweb-developer-toolbar

How to Merge Two Replace in Javascript?


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

output
19.99

Solution

  • 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).