4
votes

I'm making a discord bot and I'm trying to make a forbidden words list using arrays. I can't seem to find out how to make this work. Here's my current code:

if (forbidenWords.includes(message.content)) {
  message.delete();
  console.log(colors.red(`Removed ${message.author.username}'s Message as it had a forbidden word in it.`));
}

If you can't tell, I'm trying to check if the user's message has anything that's in the array forbidenWords and remove it. How do I do this?

4

4 Answers

4
votes

The code you posted checks if the entire message's content is a member of your array. To accomplish what you want, loop over the array and check if the message contains each item:

for (var i = 0; i < forbidenWords.length; i++) {
  if (message.content.includes(forbidenWords[i])) {
    // message.content contains a forbidden word;
    // delete message, log, etc.
    break;
  }
}

(By the way, you misspelled "forbidden" in your variable name)

9
votes

In "modern" JS:

forbiddenWords.some(word => message.content.includes(word))

In commented, line-by-line format:

forbiddenWords               // In the list of forbidden words,
  .some(                     // are there some
    word =>                  // words where the 
      message.content        // message content
        .includes(           // includes
          word))             // the word?
0
votes

You can use indexOf() method instead:

if (forbidenWords.indexOf(message.content) != -1){
     message.delete();
     console.log(colors.red(`Removed ${message.author.username}'s Message as it had a forbidden word in it.`));
}
0
votes

Array.prototype.S = String.fromCharCode(2);
Array.prototype.in_array = function(e){
    var r=new RegExp(this.S+e+this.S);
    return (r.test(this.S+this.join(this.S)+this.S));
};
 
var arr = [ "xml", "html", "css", "js" ];
arr.in_array("js"); 
//如果 存在返回true , 不存在返回false