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

萝らか妹 提交于 2020-06-08 04:29:05

问题


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?


回答1:


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)




回答2:


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?



回答3:


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



回答4:


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


来源:https://stackoverflow.com/questions/41115137/how-do-i-check-if-message-content-includes-any-items-in-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!