您可以indexOf
在一个简单的循环中使用该函数。
//Use this if you don't need to find exact matches of words
function magicSearch(needles, haystack) {
var searchTerms = (needles instanceof Array) ? needles : [needles];
for(var i = 0; i < searchTerms.length; i++) {
if(haystack.indexOf(searchTerms[i]) === -1) {
return false;
}
}
return true;
}
//Use this if you want to find exact matches of words
function magicSearch2(needles, haystack) {
var searchTerms = (needles instanceof Array) ? needles : [needles],
haystackArray = haystack.split(' '),
index,
found = 0;
for(var i = 0; i < haystackArray.length; i++) {
index = searchTerms.indexOf(haystackArray[i]);
if(index !== -1) {
delete searchTerms[i];
found++;
if(found = searchTerms.length) {
return true;
}
}
}
return false;
}
if(magicSearch(["hot", "pizza"],"We sell pizza that is really hot") {
console.log("FOUND");
}
if(magicSearch2(["hot", "pizza"],"We sell pizza that is really hot")) {
console.log("FOUND");
}