搜索一个单词并获取其上下文-jQuery

时间:2018-11-17 16:05:15

标签: jquery regex

我需要从用户输入(文本区域)中搜索字词。如果搜索是肯定的,则需要获得上下文,该上下文意味着前后几个单词,以突出显示搜索词的位置。

这是代码

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 ... ...

出于某种原因,代码考虑了单词中搜索词的出现。我需要搜索单词,在这种情况下,如果现象内出现 men ,则应将其忽略。

我怎样才能使正则表达式仅用于全字搜索?

0 个答案:

没有答案