You can use this regular expression to highlight any non-numeric or . characters: /[^\d\.]/g
So:
$('#new_price').val().replace(/[^\d\.]/g, '');
How does this regular expression work:
/ -> start of regex literal [ -> start of a "character class". Basically you're saying I to match ANY of the characters in this class. ^ -> this negates the character class which says I want anything that is NOT in this character class \d -> this means digits, so basically 0-9. \. -> Since . is a metacharacter which means "any character", we need to escape it to tell the regex to look for the actual . character ] -> end of the character class / -> end of the regex literal. g -> global flag that tells the regex to match every instance of the pattern.
So basically this is looking for everything that is NOT a digit or decimal point.
To find out if it is in the correct format, you can check if the value matches:
/\d*(\.\d{0, 2})?/
You can use it like this:
if(/^\d*(\.\d{0, 2})?$/.test($('#new_price').val()) { ... ... }
Thus, the code in the if block will only work if it matches the pattern. Here is an explanation of the regular expression:
/ -> start of regex literal ^ -> anchor that means "start of string". Yes the ^ is used as an anchor and as a negation operator in character classes :) \d -> character class that just matches digits * -> this is a regex metacharacter that means "zero or more" of the preceding. So this will match zero or more digits. You can change this to a + if you always want a digit. So instead of .99, you want 0.99. ( -> the start of a group. You can use this to isolate certain sections or to backreference. \. -> decimal point \d{0, 2} -> zero to two numbers. ) -> end of the group ? -> regex metacharacter that means "zero or one" of the preceding. So what this means is that this will match cases where you do have numbers after the decimal and cases where you don't. $ -> anchor that means "end of string" / -> end of the regex literal
source share