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

问题描述 投票:0回答:2

这个问题在这里已有答案:

我正在用Discord.js创建一个Discord僵尸程序,每当有人发帖消息时就会捕获它。我有一个阵列充满了常见的咒骂词,缩写词,种族和性辱骂等等,我希望它能够捕获。

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

(数组没有所有的标签,我只是为帖子添加了它们)

我最初尝试使用的是if (lcMsg.includes(SwearWords)) {return;},其中lcMsgmessage.content.toLowerCase();,因此它可以抓住用户咒骂,无论他们如何利用它。但这没有用,所以我尝试在谷歌回答后使用.entries().every()(我从来没有找到任何答案)。

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

javascript arrays node.js discord.js
2个回答
1
投票

数组.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而不是.some找到消息所包含的单词:

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));

0
投票

你需要使用函数some和函数includes

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

看看变量lcMsg是如何准备循环其单词的。

© www.soinside.com 2019 - 2024. All rights reserved.