Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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(.)?

like image 731
user2179950 Avatar asked Mar 17 '13 18:03

user2179950


People also ask

How do I remove all characters from a string except numbers?

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.

How to remove all non numeric characters JavaScript?

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.

How do I remove a character from a number string?

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.


1 Answers

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.
}
like image 85
Matt Cain Avatar answered Oct 05 '22 03:10

Matt Cain