AbgrundLemur
AbgrundLemur

Reputation: 35

Search String for all elements of array

I am trying to search multiple strings for every word of a search string and only show the strings that contain every word of it.

So far i managed to build a search tool that looks for the string as a whole, but i would like to search for each word individually, maybe by splitting the search string up into an array of strings.

In the example below, searching for "first" shows the first paragraph, but searching for "This first" shows nothing, because the paragraphs are searched for the whole term instead of the words "This" and "first" individually.

How can i accomplish that?

let search = document.getElementsByTagName("input")[0];

search.addEventListener("input", function() {
let s = search.value;
for (let e of search.nextElementSibling.children) {
        if (e.textContent.search(s) == -1) {
            e.style.display = "none";
        } else if (e.style.display == "none") {
            e.style.display = "block";
        }
    }
});
<html>
<head>
  <title>Title</title>
</head>
<body>
<input type="search">
<div>
<p>This is the first string.</p>
<p>This is the second string.</p>
<p>This is the third string.</p>
</div>
</body>

Upvotes: 0

Views: 450

Answers (2)

Unmitigated
Unmitigated

Reputation: 89204

You can split the text by whitespace and check if all words are contained with Array#every in conjunction with Array#includes.

let search = document.querySelector("input");
search.addEventListener("input", function() {
  let s = search.value.split(/\s+/);
  for (let e of search.nextElementSibling.children) {
    let words = e.textContent.split(/\s+/);
    if (!s.every(x => words.includes(x))) {
      e.style.display = "none";
    } else {
      e.style.display = "block";
    }
  }
});
<input type="search">
<div>
  <p>This is the first string.</p>
  <p>This is the second string.</p>
  <p>This is the third string.</p>
</div>

Upvotes: 0

Jamiec
Jamiec

Reputation: 136074

You can split the search string on space and use some and includes to determine if any of the words are in each string

let search = document.getElementsByTagName("input")[0];

search.addEventListener("input", function() {
  let s = search.value.split(" ");
  for (let e of search.nextElementSibling.children) {
    if (!s.some(x => e.textContent.includes(x)) ) {
      e.style.display = "none";
    } else if (e.style.display == "none") {
      e.style.display = "block";
    }
  }
});
<html>

<head>
  <title>Title</title>
</head>

<body>
  <input type="search">
  <div>
    <p>This is the first string.</p>
    <p>This is the second string.</p>
    <p>This is the third string.</p>
  </div>
</body>

Upvotes: 2

Related Questions