2013-11-26 86 views
1

我有一个代码在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/

+1

你可以通过提供一堆使用AND和OR的例子来澄清:“一行应该包含:john或男性还是女性”?这将帮助您准确定义您想要的内容。请更新您的问题,而不是添加新评论。 – leaf

+1

好的,先生。先生,现在已经好了。感谢您的建议:) – Vincent

+1

oopppps ..赏金无效。我只是在测试它。对不起 – Vincent

回答

3

您可以使用\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

+1

我真的应该把“\ bmale \ b”? – Vincent

+1

不,请使用'/ \ bmale \ b /' – Halcyon

+0

抱歉,我只是编程方面的新手。你见过我的jsfiddle吗? – Vincent