要查找数组中的特定单词,可以使用include()。我们有以下数组-
var sentence = ["My Name is John Smith. My Favourite Subject is JavaScript. I live in US. I like Hockey"];
现在,下面是一个数组,其中包含我们需要在上述“句子”数组中搜索的单词-
var keywords = ["John", "AUS", "JavaScript", "Hockey"];
以下是代码-
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);
要运行上述程序,您需要使用以下命令-
node fileName.js.
在这里,我的文件名为demo226.js。
输出结果
输出如下-
PS C:\Users\Amit\JavaScript-code> node demo226.js The matched keywords are== [ 'John', 'JavaScript', 'Hockey' ]