-4

This is my current code, I'm wondering whether i have to use a mess of 'else if,' or if i can keep it compact.

if (message.content.toLowerCase().includes(`word`||`word2`||`word3`||`word4`||`wd`||`wd2`||`wd3`||`wd4`)){ 
          message.reply('don\'t swear in front of me!');
          message.delete({ timeout: 100 })

}})

The issue is that only the very first string, word, is being tested for. All the other strings give no response when i type them into discord.

Lachy
  • 1
  • 2
  • That just evaluates to `.includes("word")`, which I doubt is what you want. – jonrsharpe Sep 09 '20 at 07:20
  • my issue is that only the first string is being tested for, when i type in word3 for example, the bot doesnt respond – Lachy Sep 09 '20 at 07:22
  • Yes, exactly. That's not how `||` works, only a single value is passed to includes. – jonrsharpe Sep 09 '20 at 07:26
  • Does this answer your question? [Check if an array contains any element of another array in JavaScript](https://stackoverflow.com/questions/16312528/check-if-an-array-contains-any-element-of-another-array-in-javascript) – jonrsharpe Sep 09 '20 at 07:26

1 Answers1

0

You have the right idea but you're using the || operator wrong. The || operator checks whether the statement on the left is false/null/undefined and if so, checks the statement on the right. The way you've defined it ('word'||'word2'||...), the operator takes the left statement, in this case the string 'word', and checks if it's false/null/undefined which it isn't because it's a string. Therefore it never checks any other words.

How I think you meant to use it, is like the following:

if (message.content.toLowerCase().includes(`word`) || 
    message.content.toLowerCase().includes(`word2`) ||
    message.content.toLowerCase().includes(`word3`) ||
    ...etc
){ 
    // Code here
}

In theory this would work, but as you can see yourself this is far from clean and will get big and bulky with little effort. A better approach would be with using the Array.some() function which calls a function for each item in an array and returns true when one item passes the function. Take a look at the example below:

// Define an array of all the words that need to be checked.
const arrayOfBadWords = ['word', 'word2', 'word3', ...];

if (arrayOfBadWords.some(word => message.content.toLowerCase().includes(word))) {
    message.reply('The message contains a blacklisted word.');
} else {
    message.reply('The message looks absolutely fine.');
}

T. Dirks
  • 3,566
  • 1
  • 19
  • 34