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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15346959/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 00:28:48  来源:igfitidea点击:

Regular expression for checking if string is a-zA-Z0-9

javascript

提问by timpone

I am trying to check if a string is all a-zA-Z0-9but this is not working. Any idea why?

我试图检查一个字符串是否全部,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");
}

回答by Bergi

exec()returns nullif no match is found, which is typeofobject not undefined.

exec()null如果未找到匹配项,则返回typeof对象 not undefined

You should use this:

你应该使用这个:

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

Or just use the testmethod:

或者只是使用test方法

var matchStatus = pattern.test(myString); // a boolean

回答by Shaul Hameed

If im not wrong, your regex has no provision for SPACE and your string has space in it. If you want to allow space try this way /^[a-zA-z0-9\ ]*$/

如果我没有错,您的正则表达式没有提供 SPACE 并且您的字符串中有空格。如果你想留出空间试试这种方式 /^[a-zA-z0-9\ ]*$/

回答by Ben McCormick

Try

尝试

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

if(matchStatus===1){
  alert("there was a match");
}

Regex.exec returns null if there's no match, not undefined. So you need to test that.

如果没有匹配项,则 Regex.exec 返回 null,而不是未定义。所以你需要测试一下。

It seems to work as you expect like that: fiddle

它似乎像你期望的那样工作:fiddle

Documentation for exec: MDN

文档execMDN

回答by Krucamper

function KeyString(elm)
{
    var pattern = /^[a-zA-Z0-9]*$/;

    if( !elm.value.match(pattern))
    {
        alert("require a-z and 0-9");
        elm.value='';
    }
}

回答by benqus

I would test it only - in this case:

我只会测试它 - 在这种情况下:

var pattern = /^[a-z0-9]+$/i;
var myString = '125 jXw';
var matchStatus = 1;  // say matchStatus is true

if (!pattern.test(matches)) {
    matchStatus = 0; // matchStatus is false
};

if(matchStatus === 1){
    alert("there was a match");
}