此问题已在此处有答案:
Converting user input string to regular expression(15个回答)
17天前关闭
我在本地机器上有一个页面,我使用了一个JavaScript实时过滤器脚本,我在这里得到:https://css-tricks.com/in-page-filtered-search-with-vanilla-javascript/
它非常适合我的需要,但我也希望能够使用正则表达式搜索。
目前我正在努力……
function liveSearch() {
// Locate the card elements
let cards = document.querySelectorAll('.cards')
// Locate the search input
let search_query = document.getElementById("searchbox").value;
let reg_query = /search_query/.test(cards[i].innerText)
for (var i = 0; i < cards.length; i++) {
// If the text is within the card...
if (reg_query) {
// ...remove the `.is-hidden` class.
cards[i].classList.remove("is-hidden");
} else {
// Otherwise, add the class.
cards[i].classList.add("is-hidden");
}
}
}
但这不管用。
最终,我希望能够使用普通字符串或正则表达式进行过滤。也许可以在正则表达式前加上“%:”之类的前缀。
1条答案
按热度按时间huus2vyu1#
你提供的代码有几个问题。
第一个问题是您定义
reg_query
太早了。它应该在for循环中定义。您还可以定义表达式本身,稍后再进行测试,我稍后将演示。第二个问题是在正则表达式初始化器中实际上没有使用变量
search_query
,而是创建了一个匹配字符串- well -search_query
的正则表达式。看看MDN Docs for RegExp,你可以沿着以下路线尝试一些东西:
这里有一个例子来告诉你这是如何工作的。