Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>First, we need to find first occurance of term in a string. Instead, we dealing with an array of words, so we better find first occurance of a term in such an array. I decided to attach this method to Array's prototype. We could use <code>indexOf</code>, but if we split a string by " ", we will deal with words like "rain," and <code>indexOf</code> wouldn't match it.</p> <pre><code>Array.prototype.firstOccurance = function(term) { for (i in this) { if (this[i].indexOf(term) != -1 ) { // still can use idnexOf on a string, right? :) return parseInt(i,10); // we need an integer, not a string as i is } } } </code></pre> <p>Than, I split a string by words, to do so, split it by " ":</p> <pre><code>function getExcerpt(text, searchTerm, precision) { var words = text.split(" "), index = words.firstOccurance(searchTerm), result = [], // resulting array that we will join back startIndex, stopIndex; // now we need first &lt;precision&gt; words before and after searchTerm // we can use slice for this matter // but we need to know what is our startIndex and stopIndex // since simple substitution from index could lead us to // a negative value // and adding to an index could get us to exceeding words array length startIndex = index - precision; if (startIndex &lt; 0) { startIndex = 0; } stopIndex = index + precision + 1; if (stopIndex &gt; words.length) { stopIndex = words.length; } result = result.concat( words.slice(startIndex, index) ); result = result.concat( words.slice(index, stopIndex) ); return result.join(' '); // join back } </code></pre> <p>Results:</p> <pre><code>&gt; getExcerpt("I'm singing in the rain, just singing in the rain", 'rain', 3) 'singing in the rain, just singing in' &gt; getExcerpt("I'm singing in the rain, just singing in the rain", 'rain', 2) 'in the rain, just singing' &gt; getExcerpt("I'm singing in the rain, just singing in the rain", 'rain', 10) 'I\'m singing in the rain, just singing in the rain' </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload