首页 > 解决方案 > 如何在搜索字段中将 value.val() 与正则表达式进行比较?想以多个单词为标准

问题描述

简直要疯了。我有这个代码,它非常有效:

HTML:

<p class="no-result"> Nothing found. </p>

JS:(jQuery)

$("#itemSearch").on("keyup", function () {

  if ($("#itemSearch").val() == '') {
    $(".main").show();
  }

  else {

        $(".item").filter(function () {
          $(this).toggle($(this).text().toLowerCase().search(value) > -1)

          if ($(".item").text().toLowerCase().includes(value)) {
            $(".no-result").css("display", "none");
          }
          else {
            $(".no-result").css("display", "inline");
          }

        }); 
  }
});

但是代码只向我显示了一项作为价值。我想要搜索多个单词的选项。所以我想到了这样的代码:

    var pattern = /^\b[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b$/i;
    var value = pattern.test($(this).val().trim().toLowerCase().split(" "));

拆分用于搜索多个单词/值。但我不确定正则表达式是否必要。做错了什么?

问候尔雅

标签: javascriptjqueryregexsearchfilter

解决方案


关键是在您的正则表达式中使用全局修饰符“g”来查找多个匹配项。您还必须使用text.match(pattern)而不是pattern.test(text)检索结果数组。

使用

const pattern = /([A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4})/ig;
const text= 'a@a.com  b@b.com  c@c.com';
return text.match(pattern);

我得到一个包含 3 个匹配项的数组:

[ "a@a.com", "b@b.com", "c@c.com" ]

不需要 .split() 函数,也可以跳过修剪。你应该使用:

var value = $(this).val().match(pattern);

推荐阅读