Javascript list filter – Contains any of the words instead of contains

I have a a script that currently allows me to filter a list based upon an input box. My problem is it filters based the list containing the phrase that I type in rather than containing any of the words that I type in.

Can anyone help me get me tweak this so that it filters based on contains any of the words I type in? For example, if I type in “Primary home”, it should filter any list items with the words, Primary or Home.

Currently it searches for “Primary Home” which in this example would show no matches being found.

function myFunction() {
  var input, filter, ul, li, a, i, txtValue;
  input = document.getElementById("myInput");
  filter = input.value.toUpperCase();
  ul = document.getElementById("myUL");
  li = ul.getElementsByTagName("li");
  for (i = 0; i < li.length; i++) {
    a = li[i].getElementsByTagName("a")[0];
    txtValue = a.textContent || a.innerText;
    if (txtValue.toUpperCase().indexOf(filter) > -1) {
      li[i].style.display = "";
    } else {
      li[i].style.display = "none";
    }
  }
}
<div>
  <input id="myInput" />
  <button onclick="myFunction()">Search</button>
  <ul id="myUL">
    <li><a>MY HOUSE</a></li>
    <li><a>PRIMARY CARE HOME</a></li>
  </ul>
</div>

Answer

Your code can be very much simplified. Start by using split to get an array of all the words typed into the input. Then look for any items which contains some of the search terms:

function myFunction() {
  const searchTerms = document.querySelector("#myInput").value.toUpperCase().split(" ");
  
  const listItems = document.querySelectorAll("#myUL li a");
  [...listItems].forEach(a => {
      const txtValue = (a.textContent || a.innerText).toUpperCase();
      a.parentElement.style.display = searchTerms.some(v => txtValue.indexOf(v) > -1) 
            ? "" 
            : "none";
  });
}
<div>
  <input id="myInput" />
  <button onclick="myFunction()">Search</button>
  <ul id="myUL">
    <li><a>MY HOUSE</a></li>
    <li><a>PRIMARY CARE HOME</a></li>
  </ul>
</div>