嗨,我想用JavaScript创建一个非常基本的亵渎过滤器。
我有一个名为badWords
的数组,也有一个常量叫description
。我不会检查该description
中是否包含任何不良词。
这是我到目前为止所做的。
const badWords = ["Donald Trump","Mr.Burns","Sathan"];
const description = "Mr.Burns entered to the hall."
let isInclude = false;
badWords.forEach(word=>{
if(description.includes(word)){
isInclude = true
}
})
console.log(`Is include`,isInclude)
唯一的问题是我必须遍历badWords
数组。有没有一种方法可以在不循环遍历数组的情况下完成此任务?
答案 0 :(得分:2)
使用some()
-一旦找到条件匹配项,它就会从循环中退出,因此它比循环更有效。
let isInclude = badWords.some(word => description.includes(word));
答案 1 :(得分:0)
这是正则表达式解决方案的样子:
// https://stackoverflow.com/a/3561711/240443
const reEscape = s => s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
// needs to be done only once
const badWords = ["Donald Trump","Mr.Burns","Sathan"];
const badWordsRE = new RegExp(badWords.map(reEscape).join('|'));
// testing is quick and easy
console.log("Mr.Burns entered to the hall.".match(badWordsRE)); // "Mr.Burns"
console.log("Nothing objectionable".match(badWordsRE)); // null
(如果您的坏话是实际的正则表达式,例如"Mr\.Burns"
,则省略.map(reEscape)
)
答案 2 :(得分:-4)
使用try catch
const badWords = ['Donald Trump', 'Mr.Burns', 'Sathan']
const description = 'Mr.Burns entered to the hall.'
let isInclude = false
try {
badWords.forEach(word => {
if (description.includes(word)) {
isInclude = true
throw new Error(word)
}
})
} catch (e) {
console.log(e)
}