我想使用JavaScript(可以使用jQuery)进行一些客户端验证来检查字符串是否与正则表达式匹配:
^([a-z0-9]{5,})$
理想情况下,它将是一个返回true或false的表达式 .
我是一个JavaScript新手, match() 做我需要的吗?它似乎检查字符串的一部分是否匹配正则表达式,而不是整个事物 .
match()
使用 test() 方法:
test()
var term = "sample1"; var re = new RegExp("^([a-z0-9]{5,})$"); if (re.test(term)) { console.log("Valid"); } else { console.log("Invalid"); }
如果你想要的只是一个布尔结果,请使用 regex.test() :
regex.test()
/^([a-z0-9]{5,})$/.test('abc1'); // false /^([a-z0-9]{5,})$/.test('abc12'); // true /^([a-z0-9]{5,})$/.test('abc123'); // true
...你可以从正则表达式中删除 () ,因为你不需要捕获 .
()
如果您只想知道字符串是否与正则表达式匹配,请使用 /youregexp/.test(yourString) .
/youregexp/.test(yourString)
这里's an example that looks for certain HTML tags so it'清楚 /someregex/.test() 返回一个布尔值:
/someregex/.test()
if(/(span|h[0-6]|li|a)/i.test("h3")) alert('true');
您也可以使用 match() :
if (str.match(/^([a-z0-9]{5,})$/)) { alert("match!"); }
但 test() 似乎更快,因为你可以阅读here .
Important difference between match() and test():
match() 仅适用于字符串,但 test() 也适用于整数 .
12345.match(/^([a-z0-9]{5,})$/); // ERROR /^([a-z0-9]{5,})$/.test(12345); // true /^([a-z0-9]{5,})$/.test(null); // false // Better watch out for undefined values /^([a-z0-9]{5,})$/.test(undefined); // true
let str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; let regexp = /[a-d]/gi; console.log(str.match(regexp));
6 回答
使用
test()
方法:如果你想要的只是一个布尔结果,请使用
regex.test()
:...你可以从正则表达式中删除
()
,因为你不需要捕获 .如果您只想知道字符串是否与正则表达式匹配,请使用
/youregexp/.test(yourString)
.这里's an example that looks for certain HTML tags so it'清楚
/someregex/.test()
返回一个布尔值:您也可以使用
match()
:但
test()
似乎更快,因为你可以阅读here .Important difference between match() and test():
match()
仅适用于字符串,但test()
也适用于整数 .