快疯了。我有此代码,它超级有效:
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(" "));
分割用于搜索多个单词/值。但是不确定正则表达式是否必要。怎么了?
问候Erya
关键是使用正则表达式中的global modifier 'g'查找多个匹配项。您还必须使用text.match(pattern)
而不是pattern.test(regex)
来检索结果数组。
使用中
const pattern = /([A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4})/ig;
const text = '[email protected] [email protected] [email protected]';
return text.match(pattern);
我得到一个包含3个匹配项的数组:
[ "[email protected]", "[email protected]", "[email protected]" ]