检查数组是否允许或禁止使用字符

时间:2013-11-07 05:55:24

标签: javascript arrays

我想在我的函数中添加notallowedcharacters的功能,检查我该怎么做?

var userinput = prompt('Input characters:');

var lowercase = userinput.toLowerCase();

var allowedcharacters = ["a", "b", "c", "d", "e", "f"]

var notallowedcharacters = ["g-z"] && ["!","@","#","€","£","$","%","&","?","*","/","\","|",";",":","<",">","[","]","{","-","_","^","~","`","±","§"]

function match(input, statement) {
    for (var i = 0; i < statement.length; i++) {
        if (input.indexOf(statement[i]) == -1) {
            return false;
        }
    }
    return true;
}

if (match(lowercase, allowedcharacters)){
  alert(true);
}
else{
  alert(false);
}

1 个答案:

答案 0 :(得分:0)

执行此操作的最佳方法是使用正则表达式检查要在函数中标记为非法的字符串,字符,模式。

在Mozilla文档和网络上有很多关于如何构建表达式的例子和解释,如果你需要,这可能是你想象的那么复杂,这就是为什么他们是de事实上这种事情的标准。

https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions

这可以捕获不匹配的电话号码,可以根据您的使用情况进行推断。

<button onclick="testInfo(document.getElementById('phone'));">Check</button>

var re = /(?:\d{3}|\(\d{3}\))([-\/\.])\d{3}\1\d{4}/;  // RegEx Pattern
function testInfo(phoneInput){  
    var OK = re.exec(phoneInput.value);  
    if (!OK)  
      window.alert(RegExp.input + " isn't a phone number with area code!");  
    else
      window.alert("Thanks, your phone number is " + OK[0]);  
}