我需要能够搜索用户的名字或可能的中间名和姓氏,并将其弹出在搜索结果中。如果测试用例中的用户是“Alicia Henderson”,当前使用以下代码,我可以抓取字母 A 以后的任何内容(即 Alic、Alicia Hen)。然而,我希望能够输入“H”并得到 Alicia Henderson(以及用户名中可能出现的任何其他单词的所有其他情况)。类似于 Facebook、Twitter 和许多其他出色的搜索引擎的方式.提前致谢!
$("input[name='search_users']").keyup(function(){
// Retrieve the input field text and reset the count to zero
var filter = "^" + $(this).val(), itemsFound = 0;
// Loop through each user
$(".send_to .messages .message_username").each(function(){
// If the list item does not contain the text phrase fade it out
if ($(this).text().search(new RegExp(filter, "i")) < 0) {
$(this).parent().css("display","none");
// Show the list user if the phrase matches and increase the count by 1
} else {
$(this).parent().show();
itemsFound++;
}
});
});
最佳答案
您需要将字符串 anchor 的开头替换为另一种模式,该模式将允许匹配任何空格或字符串 anchor 的开头,或者 - 如果您仅使用 ASCII 字母 - 单词边界 \b
。
您需要的正则表达式可能还需要正确转义(如果它包含 (
, )
或其他特殊的正则表达式字符。因此,这就是正则表达式应该如何转义声明:
new RegExp( "(?:^|\\s)" + this.value.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), "i" )
这里,(?:^|\\s)
是一个非捕获组 (?:...)
,它匹配字符串起始位置 (^
) 或任何空格 (\\s
) 和 this.value
特殊正则表达式字符均使用 escaping regex 进行转义。 "i"
修饰符使模式不区分大小写。
以下代码片段显示了该正则表达式的工作原理:
function filterUsers() {
var rgx = new RegExp( "(?:^|\\s)" + this.value.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), "i" );
var $el = $(".message_username").hide().filter(function() {
return rgx.test( $(this).text() );
}).show();
$(this).next("span").text("Results:"+ $el.length);
}
$("input[name='search_users']").on("input", filterUsers);
<input type="text" name="search_users"> <span></span>
<ul>
<li class="message_username">Alicia Barson</li>
<li class="message_username">Brittney Halley</li>
<li class="message_username">Alicia Henderson</li>
<li class="message_username">Sten Tong</li>
<li class="message_username">Bung Gang</li>
<li class="message_username">Jin Jang</li>
<li class="message_username">John Supreme</li>
<li class="message_username">Super Man</li>
<li class="message_username">Man Chester</li>
<li class="message_username">Super Alicia</li>
</ul>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
关于jquery - 如何将正则表达式与字符串中的任何单词匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44934191/