user2179950 user2179950 - 2 months ago 10
Javascript Question

jQuery remove all characters but numbers and decimals

var price = "$23.03";
var newPrice = price.replace('$', '')


This works, but price can also be such as:

var price = "23.03 euros";


and many many other currencies.

Is there anyway that I could leave only numbers and decimal(.)?

Answer
var newPrice = price.replace(/[^0-9\.]/g, '');

No jQuery needed. You will also need to check if there is only one decimal point though, like this:

var decimalPoints = newPrice.match(/\./g);

// Annoyingly you have to check for null before trying to
// count the number of matches.
if (decimalPoints && decimalPoints.length > 1) {
    // do whatever you do when input is invalid.
}
Comments