Implement Search Feature on a Web Page in Plain JavaScript
This article describes how to search an array of JSON objects for given keywords and display the result on a web page.
We will search a list of books. Each book object contains a title, subtitle, author, category and publisher. We want to be able to search all the fields for a set of search terms and display the result on the web page.
We will start with displaying a list of books on the webpage.
The render()
function takes an array of JSON objects as its parameter. It then maps over the array to create an HTML list of books and displays the list in <div id="app"></div>
Search Field
This will create a search field on the web page
Event listener
Add an event listener in the <script>
block to listen to the “submit” event
<script>
...
var handleSearch = function(event) {
// to be implemented
}document.addEventListener('submit',handleSearch);
</script>
Implement the search
Let’s look at the code in detail
event.preventDefault()
stops the page from reloading upon submission.
// Get the search terms from the input field
var searchTerm = event.target.elements['search'].value;
searchTerm
holds the search string entered by the user in the search box.
// Tokenize the search terms and remove empty spaces
var tokens = searchTerm
.toLowerCase()
.split(' ')
.filter(function(token){
return token.trim() !== '';
});
We split the search string into individual tokens and remove any white space.
//Example
searchTerm = "Cracking the Coding Interview"
tokens = ["cracking","the","coding","interview"]
var searchTermRegex = new RegExp(tokens.join(‘|’), ‘gim’)
creates a regular expression containing all the tokens
//Example
searchTermRegex = /cracking|the|coding|interview/gim
Following code creates a string of all the values in the book
object and assign it to bookString
variable.
// Create a string of all object values
var bookString = '';
for(var key in book) {
if(book.hasOwnProperty(key) && book[key] !== '') {
bookString += book[key].toString().toLowerCase().trim() + ' ';
}
}//Example
book = {
"title": "Cracking the coding interview",
"subtitle":"189 programming questions and solutions",
"author":"Gayle Laakmann McDowell",
"category":"Programming",
"publisher":"CareerCup, LLC"
}bookString = "cracking the coding interview 189 programming questions and solutions gayle laakmann mcdowell programming careercup, llc"
Next, we filter the books
by returning objects that matchsearchTermRegex
.
var filteredList = books.filter(function(book){ // ... Code to convert book object to a string ... // Return book objects where a match is found
return bookString.match(searchTermRegex);
});// Render the search results
render(filteredList);
If any of the search terms are present in the bookString
then we store that book
object in the filteredList
. We render the search result by calling the render()
function and passing the filteredList
to it.
Reset the list
We created a reset button with type="reset"
. When this button is clicked, a “reset” event is triggered. We listen to the “reset” event and render the original list by calling the render()
function and passing the original books
array to it.
document.addEventListener('reset', function(event){
event.preventDefault();
render(books);
});
Summary
Following is the overall summary of steps in implementing the search feature:
- Tokenize the search string
- Create a regular expression of the tokens
- Stringify the book objects
- Look for the search tokens in the stringified book objects and create a list of book objects for which a match was found.
- Render the search result