ZerterCodes
ZerterCodes

Reputation: 73

How do I check if message content includes any items in an array?

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?

Upvotes: 4

Views: 57611

Answers (4)

user663031
user663031

Reputation:

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?

Upvotes: 9

arcsin1
arcsin1

Reputation: 54

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

Upvotes: 0

Eli Skoran
Eli Skoran

Reputation: 278

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.`));
}

Upvotes: 1

qxz
qxz

Reputation: 3864

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)

Upvotes: 7

Related Questions