您可以使用此正则表达式去除任何非数字或.
字符:/[^\d\.]/g
所以:
$('#new_price').val().replace(/[^\d\.]/g, '');
这个正则表达式的工作方式如下:
/ -> 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.
所以基本上这会寻找任何不是数字或小数点的东西。
要查看它的格式是否正确,您可以检查值是否匹配:
/\d*(\.\d{0, 2})?/
你可以像这样使用它:
if(/^\d*(\.\d{0, 2})?$/.test($('#new_price').val()) {
...
...
}
因此,if
块中的代码只有在匹配模式时才会运行。这是正则表达式的解释:
/ -> 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