Pages

String searching

A common requirement for a blog is a way to search for the post having a specific text in it. A requirement that could be easily implemented considering that any string in JavaString is actually an instance of the class String, that offers a bunch of useful methods. Among them indexOf() that returns the index of the passed substring in the current string, if it is there, or -1.

First thing, let's change the HTML for our blog, adding a button and a text input element, so that the user could perform a search:

<input id="btnSearch" type="button" value="Search the blog" />
<input id="txtSearch" type="text"/>

In the script, we specify the onclick behaviour for the search button:
document.getElementById("btnSearch").onclick = searchBlog;
The search function is this:

function searchBlog() {
var element = resetBlog(); // 1.

var text = document.getElementById("txtSearch").value; // 2.
var found = false;
var yellow = false;

for(var i = 0; i < blog.length; ++i) { // 3.
if(blog[i].body.indexOf(text) != -1) { // 4.
showPost(element, i, yellow); // 5.
yellow = !yellow;
found = true;
}
}

if(!found)
showNoPost(element); // 6.
}

1. remove all elements previously in the blog section
2. get the searching text specified by the user
3. loop on all the blog items
4. call indexOf() on the current post body, looking for the search text
5. show the post - yellow is a boolean set alternatively to true and false, to alternate the text background
6. if no post has been found display a dummy element

The resetBlog() function was part of the already existing showBlog() function, I have extracted its functionality in a new function so that it could be used here too, without duplicating code:

function resetBlog() {
var element = document.getElementById("blog");

while(element.firstChild)
element.removeChild(element.firstChild);

return element;
}

The showPost() function has been redesigned to be more flexible, now the decision if the background color should be yellow is left to the caller:

function showPost(element, i, yellow) {
var newNode = document.createElement("p");
newNode.appendChild(document.createTextNode(""));
newNode.innerHTML = blog[i].toHTML();
if(yellow)
newNode.setAttribute("style", "background-color: yellow");
element.appendChild(newNode);
}

A dummy element is put as child of the passed element by this function:

function showNoPost(element) {
var newNode = document.createElement("p");
newNode.appendChild(document.createTextNode("No item selected"));
newNode.setAttribute("style", "background-color: orange");
element.appendChild(newNode);
}


More information on the JavaScript Object Oriented features in chapter nine of Head First JavaScript. The code here is heavily based on an example you can find in this fun and useful book.

No comments:

Post a Comment