似乎无论我给出什么输入,它总是只匹配1个字符.m.index在比赛中总是0,m.length总是1.我在这里做错了什么?我已尝试过(并从中删除了一些代码)http://www.regular-expressions.info/javascriptexample.html并且它按预期工作并匹配整个数字.
你可以在http://jsbin.com/aqobe看到一个实例
<html>
<head>
<script type="text/javascript">
function __numberBox__correctFormat(text,allow_float){
var r;
if(allow_float){
r=/\$?[\d,\.\W]+/;
}else{
r=/\$?[\d,\W]+/;
}
var m=r.exec(text);
if(m==null){
return false;
}
alert(m.index); alert(m.length);
if(m.index!=0 || m.length!=text.length){ //must match the whole string
return false;
}
return true;
}
</script>
</head>
<body>
Enter your name: <input type="text" id="fname" onchange="
if(__numberBox__correctFormat(this.value,true)){
alert('tis true');
}else{
alert('tis false');
}" />
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
注意我想要它接受这个输入
1234 532,134 $123 493.29
返回值Regex.exec始终是包含匹配列表的数组.在您的情况下,正则表达式将匹配整个字符串,因此返回值是一个包含匹配的1个元素的数组.
/\$?[\d,\.\W]+/.exec("$493.29")
["$493.29"]
Run Code Online (Sandbox Code Playgroud)