9

I am trying to check if a string contains certain words which I had stored in an array... however I'm new to JS, so I don't exactly know how to check all of the elements inside the Array.

Here is an Example:

const fruits = ["apple", "banana", "orange"]

I am actually checking if someone sends swearwords in a chat.

if(message.content.includes(fruits)){executed code}

However my issue is when I check for fruits it does anything but when I check for a specific element in the array like fruits[0] //returns apple it will actually check for that... So my issue / question is how do I check the string for all of the elements in the array not just apples.

Gass
  • 7,536
  • 3
  • 37
  • 41
PandaDev
  • 121
  • 11
  • Does this answer your question? [Determine whether an array contains a value](https://stackoverflow.com/questions/1181575/determine-whether-an-array-contains-a-value) – Always Helping Jun 10 '20 at 04:09
  • Can you please clarify what `message.content` is? Is it a string or is it an array? I sorta get the impression it is for example some comment a user posts in a thread, and you want to see if any of the words in your array are found within it, yes? – CrayonViolent Jun 10 '20 at 04:14
  • yes sorry, message.content is a string, it is in discord.js I had added that tag but forgot to clarify it – PandaDev Jun 10 '20 at 04:17

8 Answers8

10

Your usage of includes is wrong.

From MDN:

The includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate.

arr.includes(valueToFind[, fromIndex])

const fruits = ["apple", "banana", "orange"];
const swearWord = "orange";

// execute is available
if (fruits.includes(swearWord))
  console.log("Swear word exists.");
else 
  console.log("Swear word doesn't exist.");

To check the otherway, if string contains the array's swearword:

const fruits = ["apple", "banana", "orange"];
const swearWord = "this contains a swear word. orange is the swear word";

// execute is available
if (checkForSwearWord())
  console.log("Swear word exists.");
else
  console.log("Swear word doesn't exist.");

function checkForSwearWord() {
  for (const fruit of fruits) 
    if (swearWord.includes(fruit)) return true;
  return false;
}
Community
  • 1
  • 1
Shravan Dhar
  • 1,455
  • 10
  • 18
  • Yes however... this does work with arrays... I am trying to check if a string includes a swear word not an array... I guess if anything I could us the toarray method on the string then do what you are suggesting. – PandaDev Jun 10 '20 at 04:46
  • @PandaDev I've updated the code for both cases. Upvote it if it helps you. :) – Shravan Dhar Jun 10 '20 at 05:00
  • I already upvoted as your previous code was also an extremely helpful insight to have.. This actually works way better than what I previously had used... thank you I am actually going to consider your answer as the answer... Again Thank you so much! – PandaDev Jun 10 '20 at 05:09
  • You're welcome. As a bonus, you can use `.toLowerCase()` while comparing both strings. – Shravan Dhar Jun 10 '20 at 05:56
  • 1
    I know... I am already using it so people cant use the uppercase tricks on swearwords – PandaDev Jun 10 '20 at 05:58
  • For a large array, it might be faster to use Sets rather than Arrays - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set – James McGuigan Jun 16 '20 at 09:14
3

You got it the other way around. You have to use .includes on the data array to check if the array includes the word you are looking for.

const fruits = ["apple", "banana", "orange"]
console.log(fruits.includes("banana"))
console.log(fruits.includes("something not in the array"))
holydragon
  • 6,158
  • 6
  • 39
  • 62
  • I have a sneaking suspicion OP's `message.content` is a lot of arbitrary text they want to see if word is found within, not some exact match or itself an array. – CrayonViolent Jun 10 '20 at 04:11
  • Thank you, I had ended up figuring out that what most people are suggesting was right... it was the fact I was checking the string for the array when really I should be checking if the message has any content of the array in it – PandaDev Jun 10 '20 at 04:14
3

Reverse it:

if(fruits.includes(message.content)){executed code};

Docs for Array.includes. You are using the String.includes method. You can, alternatively, also use the indexOf method.

cyberwombat
  • 38,105
  • 35
  • 175
  • 251
  • I am going to try this real quick as I believe I did it backwards like your suggesting – PandaDev Jun 10 '20 at 04:11
  • This ended up being the best one, Thank you for the Help on this, I was aware array had that method just wasn't quite sure how to use it until you pointed it out, again Thank you!!! – PandaDev Jun 10 '20 at 04:26
3

I would use an intersection here. Just in case you don't know what that is ...

An intersection is the elements that two arrays share in common.

For example

swearWords = ["f***", "s***"];
messageWords = ["I", "am", "angry...", "f***", "and", "s***"];
let intersection = messageWords.filter(x => swearWords.includes(x));
console.log(intersection) //-> ["f***", "s***"]
0p3r4t0r
  • 623
  • 5
  • 13
  • thank you for the input... I will use this later on in code but I ended up using a simpler method by checking the arrays content in the string rather than the strings content in the array... in other words I used the array.includes rather than the string.includes method. – PandaDev Jun 10 '20 at 04:23
2

try this .

fruits.forEach(fruit => {
    if (message.content.includes(fruit)) {
        console.log('true')
        return;
    }
    console.log('false')
})

Hope this help .

Arpit Vyas
  • 2,118
  • 1
  • 7
  • 18
  • Yes this works, however I ended up using a method of arrays .includes instead of the method of strings .includes and it worked a bit easier... thank you for the input though!!! – PandaDev Jun 10 '20 at 04:16
  • Will do, also I tryed this over the one I chose as the answer and this had no errors like the other did... the other one basically had to have the array item as the first part of the string, this method was almost flawless – PandaDev Jun 10 '20 at 04:49
2

you can try to use the Array some method

const fruits = ["apple", "banana", "orange"]
const containsFruit = fruit => message.content.includes(fruit);

if(fruits.some(containsFruit)) { executed code }

containsFruit is a function that will return true if a fruit is found in the message.content

fruits.some(containsFruit) will be true if any item in the array is found to be contained in the message.content

William Ku
  • 798
  • 5
  • 17
  • This does work extremely well but I ended up going with the array.includes rather than the string.includes and it fixed my issue... however I will reference this answer in the future before asking about arrays again, thank you much!!! – PandaDev Jun 10 '20 at 04:25
1

The other way to do this is with a regular expression.

For a large message string, this may be quicker than calling .includes() in a loop vs an array (which needs to loop over the entire string each time). However this should be tested.

let fruits = ["apple", "banana", "orange"]
let fruits_regex = fruits.map(f => f.replace(/(?=\W)/g, '\\')).join('|');  // escape any special chars
// fruits_regex == "apple|banana|orange"

let message = 'apple sauce with oranges';
let matches = [ ...message.matchAll(fruit_regex) ]
// [
//   ["apple",  index:  0, input: "apple sauce with oranges", groups: undefined]
//   ["orange", index: 17, input: "apple sauce with oranges", groups: undefined]
// ]

James McGuigan
  • 7,542
  • 4
  • 26
  • 29
0
const fruits = ["apple", "banana", "orange"]
if(fruits.some(x => message.content.includes(x))){
  /* executed code */
};
kyun
  • 9,710
  • 9
  • 31
  • 66
  • Good answers contain an explanation rather than just code. Please edit to explain or your answer risks being removed. – Scransom Jun 16 '20 at 00:00