You can use $.each()
in jQuery to iterate through the terms
array, and check each of them individually against the string. In the code below, I create a new JSON object called matchedTerms
that will log the term and its index in the string. See demo here: http://jsfiddle.net/teddyrised/ktuuoprp/1/
var query = "Define what is grape juice and how to drink it?",
terms = ["define", "what is", "how to"],
matchedTerms = [];
$.each(terms, function(i,v) {
var match = query.indexOf(v);
matchedTerms.push({
'term': v,
'index': match
});
});
Even better: you can build a conditional statement in there so that the matchedTerms
will only produce a simple array. See demo here: http://jsfiddle.net/teddyrised/ktuuoprp/2/
var query = "Define what is grape juice and how to drink it?",
terms = ["define", "what is", "how to"],
matchedTerms = [];
$.each(terms, function(i,v) {
var match = query.indexOf(v);
if(match > -1) matchedTerms.push(v);
});
console.log(matchedTerms);
p/s: If you want to perform case-insensitive matches, it helps to convert the query into lowercase, i.e. newQuery = query.toLowerCase(query);