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.
The every() method executes a function for each array element. The every() method returns true if the function returns true for all elements.
In order to check whether every value of your records/array is equal to each other or not, you can use this function. allEqual() function returns true if the all records of a collection are equal and false otherwise.
To print an array of objects properly, you need to format the array as a JSON string using JSON. stringify() method and attach the string to a <pre> tag in your HTML page. And that's how you can print JavaScript array elements to the web page.
slice() method returns the selected elements in an array, as a new array object.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With