当前位置 : 首页 » 互动问答 » 正文

Check whether a string matches a regex in JS

分类 : 互动问答 | 发布时间 : 2011-07-07 05:08:50 | 评论 : 6 | 浏览 : 576766 | 喜欢 : 532

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.

回答(6)

  • 1楼
  • Use regex.test() if all you want is a boolean result:

    /^([a-z0-9]{5,})$/.test('abc1');   // false
    
    /^([a-z0-9]{5,})$/.test('abc12');   // true
    
    /^([a-z0-9]{5,})$/.test('abc123');   // true
    

    ...and you could remove the () from your regexp since you've no need for a capture.

  • 2楼
  • 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");
    }
    
  • 3楼
  • 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
    
  • 4楼
  • Use /youregexp/.test(yourString) if you only want to know whether your string matches the regexp.

  • 5楼
  • 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');
    
  • 6楼
  •  let str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
     let regexp = /[a-d]/gi;
     console.log(str.match(regexp));
    

相关阅读:

How to move an element into another element?

Set HTTP header for one request

What is the best regular expression to check if a string is a valid URL?

Remove duplicates from an array of objects in JavaScript

Can I call jquery click() to follow an <a> link if I haven't bound an event handler to it with bind or click already?

Check whether a string matches a regex in JS

Check whether a string matches a regex in JS

Check whether a string matches a regex in JS

jQuery event to trigger action when a div is made visible

Check if user is using IE with jQuery