用于检查字符串是否为a-zA-Z0-9的正则表达式

tim*_*one 1 javascript

我试图检查字符串是否全部,a-zA-Z0-9但这不起作用.知道为什么吗?

var pattern=/^[a-zA-Z0-9]*$/;
var myString='125 jXw';  // this shouldn't be accepted
var matches=pattern.exec(myString);
var matchStatus=1;  // say matchStatus is true

if(typeof matches === 'undefined'){
  alert('within here');
  matchStatus=0; // matchStatus is false
};

if(matchStatus===1){
  alert("there was a match");
}
Run Code Online (Sandbox Code Playgroud)

Ber*_*rgi 6

exec()null如果没有找到匹配则返回,而不是typeof对象undefined.

你应该用这个:

var matches = pattern.exec(myString); // either an array or null
var matchStatus = Boolean(matches);

if (matchStatus)
    alert("there was a match");
else
    alert('within here');
Run Code Online (Sandbox Code Playgroud)

或者只是使用test方法:

var matchStatus = pattern.test(myString); // a boolean
Run Code Online (Sandbox Code Playgroud)