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
You can use the
includes
string method to filter the search.Here is the approach
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
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
In this case, if your search input is ‘s’ it will only return "Serious stories".
How about using startsWith function: