代码之家  ›  专栏  ›  技术社区  ›  Crazy

如何测试字符串是否有数组项[重复]

  •  0
  • Crazy  · 技术社区  · 7 年前

    我正在用Discord创建一个Discord机器人。js,每当有人在消息中发誓时就会捕获。我有一个数组,里面充满了常见的脏话、缩写、种族和性诽谤等,我想让它捕捉到。

    const SwearWords = ["a##","ba##ard","bi###","c#ck","c#nt","d#ck","f#ck","gay","k#ke","n#gg","omfg","sh#t","wtf"];
    

    (数组没有所有的hashtag,我只是在帖子中添加了它们)

    我最初尝试使用的是 if (lcMsg.includes(SwearWords)) {return;} 具有 lcMsg 存在 message.content.toLowerCase(); 这样无论用户如何大写,它都可以捕捉到用户的咒骂。但那不起作用,所以我试着用 .entries() .every() 在谷歌搜索了一个答案后(我从未找到任何答案)。

    我想 .map() 会有用吗?我不知道,因为我还没有学会如何使用它。如果有人能帮我解决这个问题,那就太好了。

    2 回复  |  直到 7 年前
        1
  •  1
  •   CRice    7 年前

    阵列 .some 方法在这里很有用。将其与您的 .includes 要查看消息中是否存在这些词语:

    const SwearWords = ["a##","ba##ard","bi###","c#ck","c#nt","d#ck","f#ck","gay","k#ke","n#gg","omfg","sh#t","wtf"];
    
    const saltyMessage = "wtf, git gud scrub";
    const niceMessage = "gg wp";
    
    function hasBadWord(msg) {
        return SwearWords.some(word => msg.includes(word));
    }
    
    console.log("Message and has swear word?:", saltyMessage, " -> ", hasBadWord(saltyMessage));
    console.log("Message and has swear word?:", niceMessage, " -> ", hasBadWord(niceMessage));

    此外,您可以使用 .find 而不是 .一些 :

    const SwearWords = ["a##","ba##ard","bi###","c#ck","c#nt","d#ck","f#ck","gay","k#ke","n#gg","omfg","sh#t","wtf"];
    
    const saltyMessage = "wtf, git gud scrub";
    const niceMessage = "gg wp";
    
    function whichBadWord(msg) {
        return SwearWords.find(word => msg.includes(word));
    }
    
    console.log("Message and has swear word?:", saltyMessage, " -> ", whichBadWord(saltyMessage));
    console.log("Message and has swear word?:", niceMessage, " -> ", whichBadWord(niceMessage));
        2
  •  0
  •   Ele    7 年前

    您需要使用该函数 some 和功能 includes

    lcMsg.replace(/\s+/g, ' ').split(' ').some((w) => SwearWords.includes(w));
    

    看看变量 lcMsg 正在准备重复它的话。