Use Regex and JavaScript to Improve Search Results
Being able to accurately and efficiently filter search results based on a user’s input is vital for ensuring a positive and effective user experience. For this post, we will create a search bar using JavaScript, HTML and CSS. Given a list of names, we should be able to filter out names based on the user’s input.
A common way to achieve this is simply to use JavaScript’s .filter()
function and check if any of the elements .includes()
the user’s input.
filterFunction = (userInput) =>{
var filteredNames = names.filter((x)=>{
return x.includes(userInput)
} return filteredNames
}
This function checks if the user’s input matches any part of any of the names in the array. If our array of names contains ‘Tom’, ‘Jerry’, ‘Larry’, ‘Barry’, and the user types in ‘T’, the filtered list will only contain one name, because ‘Tom’ is the only name in the list that contains the letter ‘T’.
This method is pretty effective, but it’s a bit restrictive because the user has to type the exact order of letters, otherwise no results will be returned. Say the user wants to find Larry from our list of names, but accidentally types ‘Lrary’. Despite the fact that the letters are correct and the order is only off by one letter, the search results would turn up empty.