Check whether a string matches a regex in JS

2020-01-22 13:13发布

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,})$

Ideally it would be an expression that returned true or false.

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.

9条回答
Ridiculous、
2楼-- · 2020-01-22 13:46
 let str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
 let regexp = /[a-d]/gi;
 console.log(str.match(regexp));
查看更多
手持菜刀,她持情操
3楼-- · 2020-01-22 13:47

I would recommend using the execute method which returns null if no match exists otherwise it returns a helpful object.

let case1 = /^([a-z0-9]{5,})$/.exec("abc1");
console.log(case1); //null

let case2 = /^([a-z0-9]{5,})$/.exec("pass3434");
console.log(case2); // ['pass3434', 'pass3434', index:0, input:'pass3434', groups: undefined]
查看更多
\"骚年 ilove
4楼-- · 2020-01-22 13:50

Here's an example that looks for certain HTML tags so it's clear that /someregex/.test() returns a boolean:

if(/(span|h[0-6]|li|a)/i.test("h3")) alert('true');
查看更多
相关推荐>>
5楼-- · 2020-01-22 13:50

try

 /^[a-z\d]{5,}$/.test(str)

console.log( /^[a-z\d]{5,}$/.test("abc123") );

console.log( /^[a-z\d]{5,}$/.test("ab12") );

查看更多
爷、活的狠高调
6楼-- · 2020-01-22 13:57

please try this flower:

/^[a-z0-9\_\.\-]{2,20}\@[a-z0-9\_\-]{2,20}\.[a-z]{2,9}$/.test('abc@abc.abc');

true

查看更多
【Aperson】
7楼-- · 2020-01-22 13:59

Use test() method :

var term = "sample1";
var re = new RegExp("^([a-z0-9]{5,})$");
if (re.test(term)) {
    console.log("Valid");
} else {
    console.log("Invalid");
}
查看更多
登录 后发表回答