搜索和过滤jQuery中的任何单词正则表达式



我正在为一个FAQ创建一个单词过滤器,现在它工作,但只与第一个单词,我应该使用什么正则表达式来过滤任何单词?

我无法将单词传递给pattern,因为它们来自Wordpress中的高级自定义字段。

我已经尝试了很多方法,但我不是一个regex专家。

Thanks in advance

$(".search-field").keyup(function() {
var pattern = new RegExp(
"^" + this.value.replace(/([\(){}|-])/g, "\$1"),
"i"
);
$(".js-list-faq li a")
.hide()
.filter(function() {
return !!$(this).text().match(pattern);
})
.show();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
</head>
<body>
<div class="box--default">
<div class="row justify-content-center">
<div class="col-md-12">
<div class="search--form--container">
<form role="search" method="get" class="search-form" action="http://scansup.local/">
<label>
<span class="screen-reader-text">Buscar:</span>
<input type="search"class="search-field"placeholder="Buscar …"value=""name="s"
/>
</label>
<input type="submit" class="search-submit" value="Buscar" />
</form>
</div>
</div>
</div>
<div class="row">
<div class="faq__list-container">
<ul class="js-list-faq">
<li>
<a href="#heading-1" style="display: inline;">Anim Collapsible Group Item #1
</a>
</li>
<li>
<a href="#heading-2" style="display: inline;">pariatur Collapsible Group Item #2
</a>
</li>
<li>
<a href="#heading-3" style="display: inline;">cliche Collapsible Group Item #3
</a>
</li>
<li>
<a href="#heading-4" style="display: inline;">reprehenderit Collapsible Group Item #4</a
>
</li>
<li>
<a href="#heading-5" style="display: inline;"
>enim Collapsible Group Item #5
</a>
</li>
<li>
<a href="#heading-6" style="display: inline;">eiusmod Collapsible Group Item #6
</a>
</li>
<li>
<a href="#heading-7" style="display: inline;">eiusmode Collapsible Group Item #7
</a>
</li>
<li>
<a href="#heading-8" style="display: inline;">Collapsible Group Item #8</a
>
</li>
<li>
<a href="#heading-9" style="display: inline;"
>Collapsible Group Item #9</a
>
</li>
<li>
<a href="#heading-10" style="display: inline;"
>Collapsible Group Item #10</a
>
</li>
<li>
<a href="#heading-11" style="display: inline;"
>Collapsible Group Item #11</a>
</li>
<li>
<a href="#heading-12" style="display: inline;">Collapsible Group Item #12</a
>
</li>
<li>
<a href="#heading-13" style="display: inline;"
>Collapsible Group Item #13</a
>
</li>
<li>
<a href="#heading-14" style="display: inline;"
>Collapsible Group Item #14</a
>
</li>
<li>
<a href="#heading-15" style="display: inline;"
>Collapsible Group Item #15</a
>
</li>
</ul>
</div>
</div>
</div>
<script src="src/index.js"></script>
</body>
</html>

你的正则表达式错误,"^">

用这个代替:

...
var pattern = new RegExp(
this.value.replace(/([\(){}|-])/g, "\$1"), 'i'
);
...

相关内容

  • 没有找到相关文章

最新更新