检查字符串是否与JS中的正则表达式匹配 [英] Check whether a string matches a regex in JS

查看:126
本文介绍了检查字符串是否与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新手,匹配()做我需要的吗?它似乎检查字符串的一部分是否匹配正则表达式,而不是整个事物。

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:

/^([a-z0-9]{5,})$/.test('abc1');   // false

/^([a-z0-9]{5,})$/.test('abc12');   // true

/^([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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆