Check whether a string matches a regex in JS

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

    const regExpStr = "^([a-z0-9]{5,})$"
    const result = new RegExp(regExpStr, 'g').test("Your string") // here I have used 'g' which means global search
    console.log(result) // true if it matched, false if it doesn't

    0 讨论(0)
  • 2020-11-22 12:12
     let str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
     let regexp = /[a-d]/gi;
     console.log(str.match(regexp));
    
    0 讨论(0)
  • 2020-11-22 12:13

    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");
    }
    
    0 讨论(0)
  • 2020-11-22 12:13

    You can try this, it works for me.

     <input type="text"  onchange="CheckValidAmount(this.value)" name="amount" required>
    
     <script type="text/javascript">
        function CheckValidAmount(amount) {          
           var a = /^(?:\d{1,3}(?:,\d{3})*|\d+)(?:\.\d+)?$/;
           if(amount.match(a)){
               alert("matches");
           }else{
            alert("does not match"); 
           }
        }
    </script>
    
    0 讨论(0)
  • 2020-11-22 12:17

    please try this flower:

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

    true

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题