Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here is a slightly better approximation:</p> <pre><code>function getMatch(string, term) { index = string.indexOf(term) if(index &gt;= 0) { var _ws = [" ","\t"] var whitespace = 0 var rightLimit = 0 var leftLimit = 0 // right trim index for(rightLimit = index + term.length; whitespace &lt; 4; rightLimit++) { if(rightLimit &gt;= string.length){break} if(_ws.indexOf(string.charAt(rightLimit)) &gt;= 0){whitespace += 1} } whitespace = 0 // left trim index for(leftLimit = index; whitespace &lt; 4; leftLimit--) { if(leftLimit &lt; 0){break} if(_ws.indexOf(string.charAt(leftLimit)) &gt;= 0){whitespace += 1} } return string.substr(leftLimit + 1, rightLimit) // return match } return // return nothing } </code></pre> <p>This is a little bit of "greedy" hehe but it should do the trick. Note the _ws array. You could include all the white space you like or modify to use regex to check for whitespace.</p> <p>This has been slightly modified to handle phrases. It only finds the first occurrence of the term. Dealing with multiple occurrences would require a slightly different strategy.</p> <p>It occurred to me that what you want is also possible (in varying degrees) with the following:</p> <pre><code>function snippet(stringToSearch, phrase) { var regExp = eval("/(\\S+\\s){0,3}\\S*" + phrase + "\\S*(\\s\\S+){0,3}/g") // returns an array containing all matches return stringToSearch.match(regExp) } </code></pre> <p>The only possible problem with this is, when it grabs the first occurrence of your pattern, it slices off the matched part and then searches again. You also need to be careful that the "phrase" variable doesn't have any regExp characters in it(or convert it to a hex or octal representation) </p> <p>At any rate, I hope this helps man! :)</p>
 

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