When we left off, we were rendering our search results using the page title and the first 200 characters of the page. That’s pretty niave, as it doesn’t provide any context to the user if the search term doesn’t appear in those first 200 characters. Instead, we should look for the search term in the content string and show it in context. We should probably give it some emphasis too, so the user can see their search term stand out in the results.
That can get a bit complex, so let’s replace the
r.content.substring(0, 200) call while rendering results in
search.js to call a new function,
formatContent(r.content, searchTerm). Here’s what that looks like:
Now we’ll find the
searchTerm in the context string and displays the 140 characters before and after. It also handles whether we should add ellipsis to either end and surrounds all the occurrences of the
<strong> tags so they’ll pop.
Now the user knows what result is most relevant to their search, but clicking on a result isn’t the best experience. The user is dropped at the top of the page with no context about what they searched for or where it’s located in the page. It’d be great if we could highlight the occurrences of their search in the page and scroll the page to where we find a match.
To make that happen, we’ll need to tell the rest of the site that the user clicked on a search result to land on the page. If you notice from “Rendering the Results” in Part 1, we’re building the links to each search result with an additional querystring parameter,
Now, we can write some code to look for this in our site, and highlight the specified term. The user can land on any page in the site from the search result, so we need to add our highlighter somewhere global. For the TrackJS Docs, I put it in our
Wait, where did that
findAndReplaceDOMText come from? That’s another handy little library that simplifies the logic of crawling the DOM tree. You can find
findAndReplaceDOMText online at GitHub.