在包含多个单词的表格中搜索

我有一个代码在jquery中搜索多个单词。 但我在搜索男性和女性这个词时遇到了问题。 当我输入单词男性时,显示结果是女性和男性,因为单词女性包含“Fe”+“男性”字符,我将如何解决这个问题。 当我输入男性时,它应该只显示男性。 只有当我输入“男性女性”或“女性”时,才会显示女性单词

if (!RegExp.escape) { RegExp.escape = function (s) { return s.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&") }; } jQuery(function ($) { ///search this table $(' #search ').click(function () { var searchthis = new RegExp($(' #emp_search ').val().replace(/ /g,"|"), 'i'); $("table").find("tr").slice(1).each(function (index) { // var text = $(this).find("td").text().toLowerCase().trim(); var text = $.trim($(this).text()); $(this).toggle(searchthis.test(text)); }); }); }); 

这是我的演示http://jsfiddle.net/wind_chime18/ANLgD/10/

您可以使用\b来检测字边界:

 var s = "There are two sexes: female and male. males are blue, females are red"; s = s.replace(/\bmale\b/g, "smurf"); console.log(s); // There are two sexes: female and smurf. males are blue, females are red" // both female, males and females don't match \bmale\b 

没有\b你会得到:

 There are two sexes: fesmurf and smurf. smurfs are blue, fesmurfs are red 

如果您更改此行:

 var searchthis = new RegExp($(' #emp_search ').val().replace(/ /g,"|"), 'i'); 

 var searchthis = new RegExp("\\b" + $(' #emp_search ').val().replace(/ /g,"|") + "\\b", 'i'); 

有效,但这意味着搜索Jo也不会给你John