javascript - 如何在搜索字段中将 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(" "));
拆分用于搜索多个单词/值。但我不确定正则表达式是否必要。做错了什么?
问候尔雅
解决方案
关键是在您的正则表达式中使用全局修饰符“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);
推荐阅读
- windows - WinRM 连接问题?
- laravel - Laravel 5.6 单元测试从头到尾维护登录会话
- rabbitmq - Rabbitmq 重新启动后重新排队所有消息
- ios - .h 文件上的预期标识符或“(”错误
- angular - 如何在其各自的列中显示数据并按名称过滤,保持 Angular 中每一行的名称和年龄一致?
- autohotkey - 在两个显示器之间移动鼠标
- powershell - 使用 SharePoint Online PowerShell 从模板创建文档库
- fabricjs - 没有fragmentSource的FabricJS图像过滤器?
- xamarin - 单击“返回”按钮时如何在选项卡之间导航
- c# - 共享相同文本框并返回不同值的 Devexpress 组合框