Using JavaScript to Search For and Highlight Text on a Web Page

This is the page that I will be searching and replacing on. Some text will be already be highlighted because I called the highlightSearchTerms function from the "onload" event in the <body> tag. You can also highlight your own search terms by clicking the buttons below. To steal this code, just copy the JavaScript functions from the source of this page.

The highlightSearchTerms function has an optional parameter to determine whether the individual words in a search term should be highlighted separately, or if they should be treated as a phrase. By default, terms will be split and highlighted individually. SeArChEs aRe nOt cAsE-sEnSiTiVe.

Here's some text inside a div, just to show that the search and replace feature works on text blocks that are already being formatted with <div>, <font>, etc. without altering the existing formatting (other than adding the highlight). The doHighlight function that actually performs the searching and replacing uses simple logic to exclude search terms that are found within HTML tags or script blocks.

One possible use of this code is to write a JavaScript function to check the document referrer, and if someone has reached this page from a search engine, then the search terms that brought the visitor here could automatically be highlighted when the page loads by calling the function in the "onload" event of the <body> tag. You should be able to use the highlightGoogleSearchTerms function on this page as a starting point for such a thing.

A few notes about using these functions:


You are on the nsftools.com website.
http://www.nsftools.com/misc/SearchAndHighlight.htm