本文翻译自:Check whether a string matches a regex in JS
I want to use JavaScript (can be with jQuery) to do some client-side validation to check whether a string matches the regex: 我想使用JavaScript(可以使用jQuery)进行一些客户端验证来检查字符串是否与正则表达式匹配:
^([a-z0-9]{5,})$
Ideally it would be an expression that returned true or false. 理想情况下,它将是一个返回true或false的表达式。
I'm a JavaScript newbie, does match()
do what I need? 我是一个JavaScript新手, match()
做我需要的吗? It seems to check whether part of a string matches a regex, not the whole thing. 它似乎检查字符串的一部分是否匹配正则表达式,而不是整个事物。
#1楼
参考:https://stackoom.com/question/RhkF/检查字符串是否与JS中的正则表达式匹配
#2楼
这是一个查找某些HTML标记的示例,因此很明显/someregex/.test()
返回一个布尔值:
if(/(span|h[0-6]|li|a)/i.test("h3")) alert('true');
#3楼
You can use match()
as well: 你也可以使用match()
:
if (str.match(/^([a-z0-9]{5,})$/)) {
alert("match!");
}
But test()
seems to be faster as you can read here . 但是test()
似乎更快,你可以在这里阅读。
Important difference between match()
and test()
: match()
和test()
之间的重要区别:
match()
works only with strings, but test()
works also with integers. 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
#4楼
Use test()
method : 使用test()
方法:
var term = "sample1";
var re = new RegExp("^([a-z0-9]{5,})$");
if (re.test(term)) {
console.log("Valid");
} else {
console.log("Invalid");
}
#5楼
let str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
let regexp = /[a-d]/gi;
console.log(str.match(regexp));
#6楼
please try this flower: 请试试这朵花:
/^[a-z0-9\_\.\-]{2,20}\@[a-z0-9\_\-]{2,20}\.[a-z]{2,9}$/.test('abc@abc.abc');
true 真正