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?
var price = "19,99 $"
price.replace(/[^0-9,.]/g, '').replace(",",".");
console.log(price)
output
19.99
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).
You could get all digits and join with dot.
var price = "19,99 $"
price = price.match(/\d+/g).join('.');
console.log(price);
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);