我需要找到一个只允许字母数字的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);">
其他回答
对于多语言支持:
var filtered = 'Hello Привет 你好 123_456'.match(/[\p{L}\p{N}\s]/gu).join('')
console.log(filtered) // --> "Hello Привет 你好 123456"
这可以匹配大多数语言中的任何字母、数字或空格。
[…->匹配条件 [ab] ->匹配'a'或'b' \p{L} ->匹配任意语言中的任意字母 \p{N} ->匹配任意语言的任意数字 \s ->匹配空格 第一场比赛后不要停止 /u ->支持unicode模式匹配
裁判:https://javascript.info/regexp-unicode
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>
与检查有效的字母数字字符串不同,可以通过检查字符串中的任何无效字符来间接实现这一点。通过检查与有效字母数字字符串的补码匹配的任何内容来执行此操作。
/[^a-z\d]/i
这里有一个例子:
var alphanumeric = "someStringHere";
var myRegEx = /[^a-z\d]/i;
var isValid = !(myRegEx.test(alphanumeric));
注意isValid处的逻辑not运算符,因为我测试的是字符串是否为假,而不是它是否有效。
字母数字区分大小写:
if (/^[a-zA-Z0-9]+$/.test("SoS007")) {
alert("match")
}
试试这个…将字段ID替换为#name… a-z(a到z), A-Z(A到Z), 0-9(0至9)
jQuery(document).ready(function($){
$('#name').keypress(function (e) {
var regex = new RegExp("^[a-zA-Z0-9\s]+$");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (regex.test(str)) {
return true;
}
e.preventDefault();
return false;
});
});