To find specific words in an array, you can use includes(). We have the following array −
var sentence = ["My Name is John Smith. My Favourite Subject is JavaScript. I live in US. I like Hockey"];
Now, the following is an array having the words we need to search in the above “sentence” array −
var keywords = ["John", "AUS", "JavaScript", "Hockey"];
Example
Following is the code −
var keywords = ["John", "AUS", "JavaScript", "Hockey"]; var sentence = ["My Name is John Smith. My Favourite Subject is JavaScript. I live in US. I like Hockey"]; const matched = []; for (var index = 0; index < sentence.length; index++) { for (var outerIndex = 0; outerIndex < keywords.length; outerIndex++) { if (sentence[index].includes(keywords[outerIndex])) { matched.push(keywords[outerIndex]); } } } console.log("The matched keywords are=="); console.log(matched);
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo226.js.
Output
The output is as follows −
PS C:\Users\Amit\JavaScript-code> node demo226.js The matched keywords are== [ 'John', 'JavaScript', 'Hockey' ]