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

前端 未结 4 1353
一生所求
一生所求 2021-01-03 11:25

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:



        
相关标签:
4条回答
  • 2021-01-03 12:08

    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

    0 讨论(0)
  • 2021-01-03 12:11

    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 讨论(0)
  • 2021-01-03 12:23

    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)

    0 讨论(0)
  • 2021-01-03 12:25

    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 讨论(0)
提交回复
热议问题