So, to list some examples, as I understand OP, if the text of the page:
One for the money,
two for the show.
, , , .
jsfiddle, , ( , , , ).
, , , , :
, , , , .
, , , , OP .
( ) ( , ) , indexOf .
getSnippet = function(keywords, fullText) {
var keywordCount = keywords.length,
keywordIndexes = [];
for(var i=0; i < keywordCount; i++) {
var searchPos = 0;
var word = keywords[i];
var index = -1;
do {
index = fullText.indexOf(keywords[i],searchPos);
if (index >= 0) {
keywordIndexes.push({i:index, word:word});
}
searchPos = index + 1;
} while (index >= 0);
}
keywordIndexes.sort(function(a, b) { return a.i == b.i ? 0 : a.i < b.i ? -1 : 1; });
for (i=0, n=keywordIndexes.length-keywordCount; i<=n; i++) {
var foundWords = {},
foundCount = 0;
snippetStart = keywordIndexes[i].i;
for (j=i; j < keywordIndexes.length; j++) {
var word = keywordIndexes[j].word;
if (!foundWords[word]) {
foundWords[word] = true;
foundCount++;
}
if (foundCount == keywordCount) {
snippetEnd = keywordIndexes[j].i + word.length;
if (minSnippet.end - minSnippet.start > snippetEnd - snippetStart) {
minSnippet.end = snippetEnd;
minSnippet.start = snippetStart;
}
break;
}
}
}
return fullText.substring(minSnippet.start, minSnippet.end);
}
. jsfiddle.