0

I need to search terms from user inputs (textarea). Where search is positive, I would need get the context which means few words before and after to highlight back the place where the search term is found.

Here is the code

var needle = men; 
var haystack = "Only few players achieved phenomenal status in the history of game.

                We are referring to he most popular sport - football played by men. 

                The World cup football happens every four years.."
haystack = $.trim(elem.val().replace(/[\t\n]+/g,' ')); // removing new line characters
var replace_regexp = new RegExp('^.*?((([A-Za-z]+[.,]?\\s+){0,2})('+needle+')(([.,]?\\s+[A-Za-z]+){0,4})).*$', "i"); 
var match_output = haystack.replace(replace_regexp, '$2<label style="color: red">$4</label>$5');
console.log(match_output);//... .. played by men. The World cup football ... ...

.

For some reason the code considers occurrence of search term within a word. I need a word search and in this case if men occurs inside phenomenal, it should ignore.

How could I get the regular expression work for only fullword search?

user4826347
  • 783
  • 2
  • 11
  • 29

0 Answers0