我是新来的,但我的问题是:
我试图检查html输入的值是否包含数组中的禁止字。
我试过:
使用split()来转换数组中的"wordthree").
G 211
我真的不明白为什么什么都不起作用。
--当我在数组中只放一个禁止字时,它可以工作。如果我在输入元素上写了多个单词,即使数组中只有一个单词,它也不能工作。
下面是HTML:
<input id="field" type="text" size="100">
<button id="check">check</button>
<p id="announce">Message</p>这是JS:
fieldIncludes() {
let field = document.querySelector('#field'); //gets the field
let btn = document.querySelector('#check'); //gets the check-field button
let messageBox = document.querySelector('#announce'); // gets the <p> to show a message
let forbiddenWords = ['wordOne', 'wordTwo', 'wordThree'];
btn.addEventListener("click", () => {
if (field.value.includes(forbiddenWords)){
messageBox.innerHTML = "Forbidden!";
} else {
messageBox.innerHTML = "Okay :)";
}
})
}请忽略JS是在课堂上。
发布于 2020-08-18 00:50:22
includes()的参数应该是一个要检查的字符串,它不会自动在数组上循环。您可以使用.some()方法来检查它们是否匹配。
if (forbiddenWords.some(word => field.value.includes(word))) {
messageBox.innerHTML = "Forbidden!";
} else {
messageBox.innerHTML = "Okay";
}发布于 2020-08-18 00:58:19
希望我没误会你。
var str = 'you plays like a noob';
function inspect_string(str, arr){
flag = false;
arr.forEach(ar=>{
flag = str.match(new RegExp(ar)) ? true : false;
});
return flag
}
// var arr = ['noob', 'trash'];
var arr = ['nice', 'good'];
console.log(inspect_string(str, arr));https://stackoverflow.com/questions/63460373
复制相似问题