Check whether a string matches a regex in JS

后端 未结 11 2234
余生分开走
余生分开走 2020-11-22 12:02

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,})$
11条回答
  •  面向向阳花
    2020-11-22 12:19

    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.

提交回复
热议问题