我需要找到一个只允许字母数字的reg ex。到目前为止,我尝试的每个人都只在字符串是字母数字的情况下工作,意思是既包含字母又包含数字。我只想要一个既允许其中一种,又不要求两者兼得的。


当前回答

扩展字符串原型以便在整个项目中使用

    String.prototype.alphaNumeric = function() {
        return this.replace(/[^a-z0-9]/gi,'');
    }

用法:

    "I don't know what to say?".alphaNumeric();
    //Idontknowwhattosay

其他回答

与检查有效的字母数字字符串不同,可以通过检查字符串中的任何无效字符来间接实现这一点。通过检查与有效字母数字字符串的补码匹配的任何内容来执行此操作。

/[^a-z\d]/i    

这里有一个例子:

var alphanumeric = "someStringHere";
var myRegEx  = /[^a-z\d]/i;
var isValid = !(myRegEx.test(alphanumeric));

注意isValid处的逻辑not运算符,因为我测试的是字符串是否为假,而不是它是否有效。

只接受数字和字母(无空格)

函数onlyAlphanumeric (str) { str.value = str.value。replace(/\s/g, "") str.value = str.value。replace(/[^a-zA-Z0-9]/g, ""); } <div>只接受数字和字母</div> <input type="text" onKeyUp=" onlyalphannumeric (this);">

使用字符类这个词。下面是等价于a ^[a- za - z0 -9_]+$:

^\w+$

解释:

^字符串的开始 \w任意字符(A-Z, A-Z, 0-9, _)。 $ end of string

如果不想匹配下划线,请使用/[^\w]|_/g。

字母数字区分大小写:

if (/^[a-zA-Z0-9]+$/.test("SoS007")) {
  alert("match")
}
/^[a-z0-9]+$/i

^         Start of string
[a-z0-9]  a or b or c or ... z or 0 or 1 or ... 9
+         one or more times (change to * to allow empty string)
$         end of string    
/i        case-insensitive

更新(支持通用字符)

如果您需要这个regexp支持通用字符,您可以在这里找到unicode字符列表。

美国小妞example: / ^(黑a-zA-Z0-9 \ u0600——地球,随便\ u06FF u0660——\ u0669 \ u06F0——\ u06F9 _. -铝+)美元/

这将支持波斯语。