How to highlight search results with JavaScript and CSS
Welcome to Eric Wendelin’s blog! You’re guaranteed to more great Javascript tutorials easily if you subscribe via RSS.
You see it in Google search results and a lot of other sites that have good search functionality. When you perform a search, your words or phrases are highlighted in the search results making it easy for you to find the most relevant content.
Today I’m going to show you a simple way to add this to your website or blog so your users can find what they need in style. I think that this kind of thing should be implemented more often for how easy it is to implement.
Search Results JavaScript code:
function highlightOnLoad() {
// Get search string
if (/s\=/.test(window.location.search)) {
var searchString = getSearchString();
// Starting node, parent to all nodes you want to search
var textContainerNode = document.getElementById("content");
// Informational message for search
var searchInfo = 'Search Results for: ';
// Split search terms on '|' and iterate over resulting array
var searchTerms = searchString.split('|');
for (var i in searchTerms) {
// The regex is the secret, it prevents text within tag declarations to be affected
var regex = new RegExp(">([^<]*)?("+searchTerms[i]+")([^>]*)?<","ig");
highlightTextNodes(textContainerNode, regex, i);
// Add to info-string
searchInfo += ' <span class="highlighted term'+i+'">'+searchTerms[i]+'</span> ';
}
// Create div describing the search
var searchTermDiv = document.createElement("H2");
searchTermDiv.className = 'searchterms';
searchTermDiv.innerHTML = searchInfo;
// Insert as very first child in searched node
textContainerNode.insertBefore(searchTermDiv, textContainerNode.childNodes[0]);
}
}
// Pull the search string out of the URL
function getSearchString() {
// Return sanitized search string if it exists
var rawSearchString = window.location.search.replace(/[a-zA-Z0-9\?\&\=\%\#]+s\=(\w+)(\&.*)?/,"$1");
// Replace '+' with '|' for regex
// Also replace '%20' if your cms/blog uses this instead (credit to erlando for adding this)
return rawSearchString.replace(/\%20|\+/g,"\|");
}
function highlightTextNodes(element, regex, termid) {
var tempinnerHTML = element.innerHTML;
// Do regex replace
// Inject span with class of 'highlighted termX' for google style highlighting
element.innerHTML = tempinnerHTML.replace(regex,'>$1<span class="highlighted term'+termid+'">$2</span>$3<');
}
// Call this onload, I recommend using the function defined at: http://untruths.org/technology/javascript-windowonload/
addOnLoad(highlightOnLoad());
Now, the highlighting CSS:
span.highlighted {
background-color: #161616;
font-weight: bold;
}
span.term0 {
background-color: #161633;
}
span.term1 {
background-color: #331616;
}
span.term2 {
background-color: #163316;
}
Code explanation
First, the highlightOnLoad() function checks window.location.search to see if we need to be running any of this stuff, then calls getSearchString to get a sanitized search string so that nothing funky can happen if, say, the user searches for ‘<script>’. You should really be sanitizing all search inputs at least on the back-end anyway.
Then, the highlightTextNodes function uses a regex replace on our textContainerNode’s innerHTML. The regex verifies that the text is between a > and a < (and not the other way around). Actually nice and simple!
Caveats
This may end up being a bit slow if you are doing this on a LOT of text, but for my blog text, it seems quite snappy to me. Also, the CSS does not bold text inside links, but the background color is there to make it obvious.
What do you think? Try it out on the search box on the upper-right. I’m hoping for some optimizations in the comments.
[...] How to highlight search results with JavaScript | Eric WendelinUse the combination of a JavaScript snippet and CSS-style to highlight words or phrases in the search results making it easier for your visitors to find the most relevant content on your weblog. [...]
[...] How to highlight search results with JavaScript | Eric Wendelin [...]
[...] http://eriwen.com/javascript/highlight-search-results-with-js/ [...]
[...] Just caught this nice code example from Eric Wendelin. Looks great, bookmarking for future reference. Tags: Javascript [...]
thank .. ^^;
[...] Arama sonuçlarını javascript ve css ile belirgin hale getirmek. Bağlantı [...]
Just one thing.. If the search contains multiple words in my experience the highlighting becomes erratic.
I modified the script so it iterates through multiple search terms one at a time:
var searchTerms = searchString.split(’|');
for ( var i = 0; i ([^]*)?$1$2$3<’);
}
Aaaand my code got eaten.. :-(
[...] I wanted to mention that one of our brilliant readers, erlando, has made a nice suggestion for Highlighting Search Results script that makes it even better! It really is quite brilliant so [...]
[...] highlight search results with javascript [...]
@erlando
remember to ad !important behind every change. Here is my example:
@namespace url(http://www.w3.org/1999/xhtml);
@-moz-document domain(”www.google.com”) {
span.highlighted {
background-color: #161616 !important;
font-weight: bold !important;
}
span.term0 {
background-color: #161633 !important;
}
span.term1 {
background-color: #331616 !important;
}
span.term2 {
background-color: #163316 !important;
}
span.term0 {
background-color: #161633 !important;
}
span.term1 {
background-color: #331616 !important;
}
span.term2 {
background-color: #163316 !important;
}
@Daniel:
I’m sorry if this is a dumb questions but, why would adding !important be uh… important? I know that it overrides any user styles but I try to avoid this when I can.
[...] to show you a simple way to add this to your website so your users can find what they need in style.http://eriwen.com/javascript/highlight-search-results-with-js/Welcome to Discovery Education School Resources! School Resources …Create and print customized [...]
Okay javascript is all new for me–but to see this code actually work I should be able to just put it all in the head of an embedded css page, right? I did that and it it didn’t do anything so I don’t know. I could not find any code in there for a search box or any other prompt. please help.
Thanks
@Mike++:
OK so all you need to use this is to copy the javscript code at the top into a <script> tag in the HEAD of our HTML. Replace the last line (addOnLoad…) to
window.onload = highlightOnLoad;
Then you need to copy the CSS into a <style type=’text/css’> tag in the HEAD tag as well.
It should work out. Let me know if you have other problems with it.
[...] A more recent attempt by Eric Wendelin - I like this one! [...]
Will try it script, Thanks for sharing
Hi Eric,
Thanks for this, it looks great (and sorry I’m late finding it). I’m struggling to get it working on a Rails app. I’ve created a searchhi.js file which I’ve included in my , and I’ve swapped over the ‘content’ div for ‘main’, but I’m still not having any luck. Do I need to give my search form or submit a specific ID? And is there a quick highlight method or some tester method I could introduce near the start of the file to make sure it is at least included properly and getting some of the way through?
Neil
@Neil:
A couple notes on this script:
- I programmed it to look for the text after ?s= or &s= in the URL. If you used something else you’ll have to update the getSearchString() function.
- The addOnLoad() is a function call at the end does not exist by default. It is just a placeholder for your initialization code. If you want, just replace it with:
window.load = highlightOnLoad;- You need the “name” attribute of your search field to be “s”
Hope that helps.
Thanks Eric. That does help - it confirms I was nearly on track (to some extent) when trying to work out how to match it to my scenario. I got as far as failing to extract the search terms from the #searchinput DOM element, but I was struggling with just getting the search terms out (js newbie ahoy, and it has been a few days since I looked at this);
var search_params = $(’searchinput’).innerHTML;
I mentioned the problem to one of my js savvy friends and he suggested I get on the prototype forums - so I’ll do that and post back here if I find a way of augmenting this script to extract the search terms from my params hash carried over to the input, rather than the URL.
How about this implementation?
HTML Search Text and Highlight
I’ve gotten mine working, with a little tweaking to my code (e.g. renaming my search input to “s”.). I was wondering how to be able to resume using “search” as my input id? I looked at line 03 above:
if (/s\=/.test(window.location.search)) {
and wondered if changing “s” to “search” there would work, but it didn’t…can this be accomplished here?
Thanks - Louis
@Louis:
You need to change line 34 (in getSearchString()) as well as line 3. Hope that helps :)
Hi Eric
Great script!
If one searches for “firefox fire”, things get marked as they should, but if one searches for “fire firefox”, the marking first put on “firefox” by “fire” (”firefox”) will prevent “firefox” from being marked. All highlighting scripts I have seen have this problem. Do you have a solution?
Jens
Thanks Eric!
Eric,
Just a (nother) question. :-)
I have a multi-page result search page, and in the display of “results found” is included the “&” which follows the search terms in the query string. I’ve tried splitting this, but nothing has been successful thus far. Do I need to use another method rather than getSearchString?
Thanks,
Louis
Eric,
Please let me clarify - in the previous post, I was meaning to specify that in the “Search Results” area, I also get the information that follows the search terms in the querystring (i.e. “page” and “operator”), but I would like to keep that data from appearing on the page. Any thoughts about the best way to do this?
Many thanks,
Louis
How to link to an anchor and highlight the search?
Like this;
Categories
In most cased highlighting the search is cool but not if you can’t jump to it.
Cheers