Check whether a string matches a regex in JS

后端 未结 11 2068
余生分开走
余生分开走 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:23

    Use /youregexp/.test(yourString) if you only want to know whether your string matches the regexp.

    0 讨论(0)
  • 2020-11-22 12:24

    try

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

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

    0 讨论(0)
  • 2020-11-22 12:26

    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]
    
    0 讨论(0)
  • 2020-11-22 12:31

    You can use match() as well:

    if (str.match(/^([a-z0-9]{5,})$/)) {
        alert("match!");
    }
    

    But test() seems to be faster as you can read here.

    Important difference between match() and test():

    match() works only with strings, but test() works also with integers.

    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
    
    0 讨论(0)
  • 2020-11-22 12:34

    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');
    
    0 讨论(0)
提交回复
热议问题