Javascript函数需要允许数字,点和逗号 [英] Javascript function need allow numbers, dot and comma
问题描述
功能需要允许数字点和逗号。所以任何人都可以修复我的正则表达式变量?谢谢。 :)函数:
pre $ function(on(evt){
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode(key);
var regex = /[0-9]|\./;
if(!regex.test(key)){
theEvent.returnValue = false;
if(theEvent.preventDefault)theEvent.preventDefault();
}
}
首先你的正则表达式目前不允许使用逗号,这是你的要求。其次,你没有使用任何量词,所以你的正则表达式只会匹配一个字符 - 一个 [0-9]
或点
。你需要使用一个量词。第三,不是使用 pipe
,你可以移动字符中的所有字符
尝试使用下面的正则表达式:
/ ^ [0-9。,] + $ /
量词 +
用于匹配1个或多个出现的模式。
^
和 $
anchor分别匹配字符串的开始和结束。
function need to allow numbers dot and comma. So anyone can repair me regex variable? Thanks. :) FUNCTION:
function on(evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode( key );
var regex = /[0-9]|\./;
if( !regex.test(key) ) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}
Firstly your regex currently doesn't allow comma, which is your requirement.
Secondly, you haven't used any quantifier, so your regex will match only a single character - one of [0-9]
or a dot
. You need to use a quantifier.
Thirdly, instead of using pipe
, you can move all characters inside the character class only.
Try using the below regex:
/^[0-9.,]+$/
Quantifier +
is used to match 1 or more occurrence of the pattern.
^
and $
anchors match the beginning, and end of the string respectively.
这篇关于Javascript函数需要允许数字,点和逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!