检查字符串是否与 JS 中的正则表达式匹配 [英] Check whether a string matches a regex in JS
本文介绍了检查字符串是否与 JS 中的正则表达式匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用 JavaScript(可以使用 jQuery)来做一些客户端验证来检查字符串是否与正则表达式匹配:
I want to use JavaScript (can be with jQuery) to do some client-side validation to check whether a string matches the regex:
^([a-z0-9]{5,})$
理想情况下,它是一个返回 true 或 false 的表达式.
Ideally it would be an expression that returned true or false.
我是 JavaScript 新手,match()
能满足我的需求吗?它似乎检查字符串的一部分是否与正则表达式匹配,而不是整个事情.
I'm a JavaScript newbie, does match()
do what I need? It seems to check whether part of a string matches a regex, not the whole thing.
推荐答案
使用 regex.test()
如果你只想要一个布尔结果:
Use regex.test()
if all you want is a boolean result:
console.log(/^([a-z0-9]{5,})$/.test('abc1')); // false
console.log(/^([a-z0-9]{5,})$/.test('abc12')); // true
console.log(/^([a-z0-9]{5,})$/.test('abc123')); // true
...并且您可以从正则表达式中删除 ()
,因为您不需要捕获.
...and you could remove the ()
from your regexp since you've no need for a capture.
这篇关于检查字符串是否与 JS 中的正则表达式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文