skip to Main Content

I want to filter search results based on the input. so far I only filter starting with the first word typed and Im not sure how to filter based on (possible) multiple words/inputs.
If I search for example: "funny stories" and one of the book name is stories, I want to return that as a match, just like when input is "funny". With my current code I would only return said book if I start typing funny.

const filteredSuggestions = suggestions
    .filter(({name}) => {
            const match = name.substr(0, searchInput.length);
            return match && match.toLowerCase() === searchInput.toLowerCase();
});

I tried (its not working):

const filteredSuggestions = suggestions
    .filter(({name}) => {
         const nameArr = name.split(" ");
        nameArr.map(name => {
            const match = name.substr(0, searchInput.length);
            return match && match.toLowerCase() === searchInput.toLowerCase();
        })
});

2

Answers


  1. You can use the includes string method to filter the search.
    Here is the approach

    const filteredSuggestions = suggestions
        .filter(({name}) => {
                return name?.toLowerCase().includes(searchInput.toLowerCase())
    });

    This will match all words including the input at any position.

    But if you want to match only those words whose first letter is matching with the input value then you can use RegExp.

    For example

    const regex = new RegExp(`\b${userInput}`, "i");
    const filteredSuggestions = suggestions
        .filter(({name}) => {
                return regex.test(result)
    });

    In this case, if your search input is ‘s’ it will return both "Funny stories", and "Serious stories". As it will match the first letter of any word in the search result.

    But if you want to match only the first letter of the first word of search results then you can use the below RegExp

    const regex = new RegExp(`^${userInput}`, "i");
    

    In this case, if your search input is ‘s’ it will only return "Serious stories".

    Login or Signup to reply.
  2. How about using startsWith function:

    const books = [
      'funny stories',
      'tales',
      'science',
      'medicine'
    ],
    display = document.getElementById('display'),
    input = document.getElementById('input'),
    results = document.getElementById('results');
      
    display.innerHTML = JSON.stringify(books);
    
    function onSearch(event)
    {
      const value = event.target.value.trim();
    
      if( value )
      {
        const filtered = books.filter(book => book.startsWith(value));
        results.innerHTML = filtered.length ? JSON.stringify(filtered) : '';
      }
      else
      {
        results.innerHTML = "";
      }
    }
    <div id="display">
    
    </div>
    
    <br>
    
    <input id="input" onkeyup="onSearch(event)" type="text">
    
    <br> <br>
    
    <div id="results">
    
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search