且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

带有正则表达式的.match()返回null

更新时间:2022-01-18 21:20:30

你想要 RegExp .test ,它测试匹配的值而不是检索匹配。使用现有代码,这意味着:

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.');
}

然而,***使用RegExp文字而不是字符串,因为它们'效率更高,更清晰,更不容易出错:

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.');
}

更好的是,使用字典:

var expressions = {
    ALPHA: /^[a-zA-Z]+$/,
    NUMERIC: /^[0-9]+$/,
    ALPHANUMERIC: /^[a-zA-Z0-9]+$/
};

if(!expressions[type].test(value)) {
    alert('Your string was invalid.');
}