regex JavaScript:在表单输入标记中使用字符串或正则表达式的实时过滤器[重复]

mbzjlibv  于 12个月前  发布在  Java
关注(0)|答案(1)|浏览(83)

此问题已在此处有答案

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");
    }
  }
}

但这不管用。
最终,我希望能够使用普通字符串或正则表达式进行过滤。也许可以在正则表达式前加上“%:”之类的前缀。

huus2vyu

huus2vyu1#

你提供的代码有几个问题。
第一个问题是您定义reg_query太早了。它应该在for循环中定义。您还可以定义表达式本身,稍后再进行测试,我稍后将演示。
第二个问题是在正则表达式初始化器中实际上没有使用变量search_query,而是创建了一个匹配字符串- well -search_query的正则表达式。
看看MDN Docs for RegExp,你可以沿着以下路线尝试一些东西:

// Match the word specifically...
let regex = RegExp(search_query);
// Or, match any text containing the term...
let regex = RegExp(`.*${search_query}.*`);

这里有一个例子来告诉你这是如何工作的。

// Some example values
const cards = ["value a", "value b", "item c", "object d", "another value e"]

const search_term = "value";
const search_exp = RegExp(`.*${search_term}.*`);
for(const card of cards) {
  if(search_exp.test(card)) {
    console.log(`Show: "${card}"`);
  } else {
    console.log(`Hide: "${card}"`);
  }
}

相关问题