Hi I would like to know how to check if the exact words contained in an array in Javascript are present in a string, like this
let filter = ["action", "romance"];
let genres = "action sci-fi romance horror";
this should be true
Hi I would like to know how to check if the exact words contained in an array in Javascript are present in a string, like this
let filter = ["action", "romance"];
let genres = "action sci-fi romance horror";
this should be true
As stated by @jabaa, you can use every
and includes
:
const matches = filter.every((word) => genres.includes(word));
First, split the string into words by splitting at a word boundary:
const splitGenres = genres.split(/\b/)
This will also put things between words like punctuation and spaces into elements, but you probably don't need to care about them because you are searching for specific known values.
If you need to normalize case and always match to lower-case values, you can also convert the results to lower-case by appending .map(word => word.toLowerCase())
to the line above (mapping each element to its lower case representation). If your filter may also not be normalized yet, you can do the same to the filter array as well.
This whole method is under the assumption that the input string can have any format like a regular sentence. If this isn't the case and instead it's always a list separated by a single space, then you can also use .split(' ')
instead.
Then, check whether all of the words in your filter array are also contained in the list of words which we have now extracted:
const allMatching = words.every(word => splitGenres.includes(word))
You then have a boolean in allMatching
telling you whether your filter matches or not.
You could use Regex with map.
let filter1 = ["action", "romance"];
let filter2 = ["action", "romance", "not_present"];
let genres = "action sci-fi romance horror";
function isAllWordPresent(str, arr) {
let count = 0;
const result = arr.map((s) => {
const regex = new RegExp(`\\b${s}\\b`);
const result = regex.test(str);
if (result) count++;
return result;
});
return result.length === count;
}
console.log(isAllWordPresent(genres, filter1));
console.log(isAllWordPresent(genres, filter2));