[英]Javascript simple regexp doesn't work
I have this code, it looks alright and is really basic, but i can't make it work:我有这个代码,它看起来不错,而且非常基本,但我无法让它工作:
function checkValid(elem){
var abc = elem.value;
var re = "/[0-9]/";
var match = re.test(abc);
alert(match);
}
It matches 0 and 9, but not 1 to 8, what's wrong here?它匹配 0 和 9,但不匹配 1 到 8,这里有什么问题? Thanks.
谢谢。
re
is a string, not a RegExp object. re
是一个字符串,而不是一个 RegExp 对象。
You need to use a regex literal instead of a string literal, like this:您需要使用正则表达式文字而不是字符串文字,如下所示:
var re = /[0-9]/;
Also, this will return true for any string that contains a number anywhere in the string.此外,对于在字符串中的任何位置包含数字的任何字符串,这都将返回 true。
You probably want to change it to你可能想把它改成
var re = /^[0-9]+$/;
尝试删除双引号...
var re = /[0-9]/;
Use \\d to match a number and make it a regular expresison, not a string:使用 \\d 匹配数字并使其成为常规表达式,而不是字符串:
var abc = elem.value;
var re = /\d/;
var match = re.test(abc);
alert(match);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.