[英]How to test if a string contains a number with regular expression in javascript?
I'm trying with 我正在尝试
function hasANumber(value) {
return /^.*[0-9]*.*$/.test(value);
}
Where I was wrong? 我哪里错了?
*
in regex means zero or more *
在正则表达式中表示零或更多
You should have used +
which means one or more, as in: 您应该使用
+
表示一个或多个,例如:
/^.*[0-9]+.*$/
Although this can be simplified to: 尽管可以简化为:
/[0-9]+/
Just \\d
would be enough for this case. 对于这种情况,只需
\\d
就足够了。
> /\d/.test('foo')
false
> /\d/.test('fo1o')
true
[0-9]*
in your regex matches a digit zero or more times, so it would allow also the strings which won't have a digit. 正则表达式中的
[0-9]*
与一个数字匹配零次或多次,因此它也将允许没有数字的字符串。
这是写数字正则表达式的正确形式:
\d+$
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.