簡體   English   中英

用於檢查字符串是否為a-zA-Z0-9的正則表達式

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

我正在嘗試檢查字符串是否全部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");
}

如果未找到匹配項,則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');

或者只是使用test方法

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

如果我沒有記錯,則您的正則表達式沒有SPACE的准備,並且字符串中有空格。 如果要允許空間,請嘗試這種方式/ ^ [a-zA-z0-9 \\] * $ /

嘗試

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

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

如果沒有匹配項,則Regex.exec返回null,即未定義。 因此,您需要測試一下。

它似乎可以按您期望的那樣工作: 提琴

exec文檔: MDN

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

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

我只會測試-在這種情況下:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM