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(.)?
To remove all characters except numbers in javascript, call the replace() method, passing it a regular expression that matches all non-number characters and replace them with an empty string. The replace method returns a new string with some or all of the matches replaced.
In order to remove all non-numeric characters from a string, replace() function is used. replace() Function: This function searches a string for a specific value, or a RegExp, and returns a new string where the replacement is done.
Using 'str. Using str. replace() , we can replace a specific character. If we want to remove that specific character, replace that character with an empty string. The str.
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.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With