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

search in a table with multiple words

本文关键字:搜索 单词 包含多      更新时间:2023-10-26

我有一个在jquery中搜索多个单词的代码。但是我在搜索单词male和female时遇到了一个问题。当我输入单词"男性"时,显示结果是女性和男性,因为单词"女性"包含"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