.match() with a regular expression returns null

前端 未结 3 2070
遥遥无期
遥遥无期 2020-12-17 08:29

I am trying to do something I thought would be pretty easy to do, which is to restrict a string to certain characters by matching a regular expression.

var v         


        
相关标签:
3条回答
  • 2020-12-17 08:56

    Regex must be surrounded with /, not ', so that JavaScript creates a variable of type regex, not of type string. So for instance, for your ALPHA case, you should have

    regex = /^[a-zA-Z]+$/;
    

    See MDN's page on .match for more information about using .match.

    0 讨论(0)
  • 2020-12-17 09:02

    Your code looks like it's inside a function { ... }. Are you returning anything? If not, that's why you're getting null back...

    Also, regexes are surrounded by slashes (/.../), not quotes.

    0 讨论(0)
  • 2020-12-17 09:11

    You want RegExp.test, which tests a value for a match instead of retrieving the match. With your existing code, that would mean:

    if(!new RegExp(regex).test(value)){
        alert('Your string was invalid.');
    }
    

    However, it would be preferable to use RegExp literals instead of strings, as they're much more efficient and clear, and less prone to error:

    var value = 'FailureStr1ng';
    var type = 'ALPHA';
    var regex = null;
    
    switch(type) {
        case 'ALPHA':
            regex = /^[a-zA-Z]+$/;
            break;
        case 'NUMERIC':
            regex = /^[0-9]+$/;
            break;
        case 'ALPHANUMERIC':
            regex = /^[a-zA-Z0-9]+$/;
            break;
    }
    
    if(!regex.test(value)) {
        alert('Your string was invalid.');
    }
    

    Even better, use a dictionary:

    var expressions = {
        ALPHA: /^[a-zA-Z]+$/,
        NUMERIC: /^[0-9]+$/,
        ALPHANUMERIC: /^[a-zA-Z0-9]+$/
    };
    
    if(!expressions[type].test(value)) {
        alert('Your string was invalid.');
    }
    
    0 讨论(0)
提交回复
热议问题