0

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>

2 Answers 2

2

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>

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! Turns out I need s.every instead of s.some but the rest works perfectly fine :)
@AbgrundLemur ah right I thought you wanted an or search but yes if you want an and search it is indeed every
0

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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.