我正在制作一个用户注册页面,我不希望任何与该数组不匹配的字符。
function create(){
var allowed = [
"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z",
"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z",
"1","2","3","4","5","6","7","8","9","0","_","-"];
var username = $("#username").val();
if (username == ""){
document.getElementById("usernameerror").style.color = "red";
document.getElementById("usernameerror").innerHTML = " Username cannot be blank.";
}else{
if (username.indexOf(allowed) != -1){
document.getElementById("usernameerror").style.color = "red";
document.getElementById("usernameerror").innerHTML = " No symbols.";
}else{
document.getElementById("usernameerror").style.color = "blue";
document.getElementById("usernameerror").innerHTML = " ✔";
}
}
}
我敢打赌它很简单......(不是子字符串)
答案 0 :(得分:3)
这正是regular expressions旨在解决的问题。尝试替换此行:
if (username.indexOf(allowed) != -1){
......用这个:
if (!/^[a-z0-9_-]*$/i.test(username)) {
您的要求也与\w
metacharacter非常相似,这样您就可以将其用于正则表达式:
/^[\w-]+$/
答案 1 :(得分:2)
怎么样:
if (username.match(/[^\w-]/) !== null) {
console.log('username has non-word characters...');
}

请参阅此处了解\ w的作用:MDN Regular Expression。
答案 2 :(得分:0)
检查出来:
if (/^[a-z0-9\-\_]+$/.test(username)) {
document.getElementById("usernameerror").style.color = "red";
document.getElementById("usernameerror").innerHTML = " No symbols.";
}else{
document.getElementById("usernameerror").style.color = "blue";
document.getElementById("usernameerror").innerHTML = " ✔";
}