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


当前回答

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

函数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);">

其他回答

字母数字区分大小写:

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

JAVASCRIPT只接受数字,字母和特殊字符

document.getElementById("onlynumbers").onkeypress = function (e) { onlyNumbers(e.key, e) }; document.getElementById("onlyalpha").onkeypress = function (e) { onlyAlpha(e.key, e) }; document.getElementById("speclchar").onkeypress = function (e) { speclChar(e.key, e) }; function onlyNumbers(key, e) { var letters = /^[0-9]/g; //g means global if (!(key).match(letters)) e.preventDefault(); } function onlyAlpha(key, e) { var letters = /^[a-z]/gi; //i means ignorecase if (!(key).match(letters)) e.preventDefault(); } function speclChar(key, e) { var letters = /^[0-9a-z]/gi; if ((key).match(letters)) e.preventDefault(); } <html> <head></head> <body> Enter Only Numbers: <input id="onlynumbers" type="text"> <br><br> Enter Only Alphabets: <input id="onlyalpha" type="text" > <br><br> Enter other than Alphabets and numbers like special characters: <input id="speclchar" type="text" > </body> </html>

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

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

用法:

    "I don't know what to say?".alphaNumeric();
    //Idontknowwhattosay
/^([a-zA-Z0-9 _-]+)$/

上面的正则表达式允许字符串中有空格并限制特殊字符。它只允许 a-z, a-z, 0-9,空格,下划线和破折号。

我有类似于三星Galaxy A10s 6.2英寸(2GB,32GB ROM) Android 9.0,(1300万+ 200万)+ 800万双卡4000mAh 4G LTE智能手机-黑色(BF19)

以下是我所做的:

string.replace(/[^a-zA-Z0-9 ,._-]/g, '').split(',').join('-').split(' ').join('-').toLowerCase()

注意,i允许。然后使用split()和join()分别替换,to -和空格to -。

我最终得到了这样的东西: samsung-galaxy-a10s-6.2英寸-2gb-32gb-rom-android-9.0-13mp-2mp-8mp-dual-sim-4000mah-4g-lte-smartphone-black-bf19-20,这就是我想要的。

可能有更好的解决方案,但这是我发现工作对我很好。