Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
317 views
in Technique[技术] by (71.8m points)

javascript - .match() with a regular expression returns null

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 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;
}

return value.match(regex);

For some reason, when using the match it always returns null. Is there a way to fix this, or a better method to do this?

Note: The code here is a snippet of much larger code, and in turn the value and type variable are usually defined by another method.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...