Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Tìm từ khóa cụ thể trong mảng - JavaScript

Dùng includes() để tìm các từ khóa trong chuỗi.

Mã thực hiện

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 i = 0; i < sentence.length; i++) {
  for (var j = 0; j < keywords.length; j++) {
    if (sentence[i].includes(keywords[j])) matched.push(keywords[j]);
  }
}
console.log("The matched keywords are==");
console.log(matched);

Kết quả

The matched keywords are== [ 'John', 'JavaScript', 'Hockey' ]