带有正则表达式的.match()返回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);
出于某种原因,当使用匹配时,它总是返回 null
。有没有办法解决这个问题,或者有更好的方法来解决这个问题?
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.
你想要 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.');
}