JavaScript简单脏话过滤器

xxhby3vn  于 2023-03-16  发布在  Java
关注(0)|答案(4)|浏览(153)

嗨,我想在JavaScript中创建一个非常基本的脏话过滤器。
我有一个数组,叫做badWords,还有一个常量,叫做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数组,有没有办法不用遍历数组就可以完成这个任务?

zaqlnxep

zaqlnxep1#

使用some()--它会在找到条件匹配项后立即退出循环,因此它比循环性能更高。

let isInclude = badWords.some(word => description.includes(word));
bxpogfeg

bxpogfeg2#

regexp解决方案如下所示:

// 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

(If不好的单词是实际的正则表达式,如"Mr\.Burns",然后省略.map(reEscape)

f8rj6qna

f8rj6qna3#

这个函数我做了把坏字变成****,如果坏字是5个字母,它会把5 * 的
(this是为我的聊天我编码)

function filter(chat) {
    var cusswords = ["badword1", "badword2"]
    var chat; // define the chat var which is the function parameter
    for(i=0; i < cusswords.length; i++) {
        var length = String(cusswords[i]).length;
        var characters = "";
        for(u=0; u < length; u++) {
            characters = String(characters) + String("*");
        }
        chat = chat.replace(String(cusswords[i]), String(characters));
    }
    console.log(chat)
    return chat;
}

那么你只需要在filter()函数中使用一个var,它等于你想要过滤的文本。

var cleanChat = filter(chat);

// send(cleanChat) then send it with another function.
ig9co6j1

ig9co6j14#

使用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)
}

相关问题