I have the following script which works well and highlights all occurrences of the search term wherever it appears in bodyText: beginning, middle, or end of words.
How do I go about limiting its hits to either words [B]beginning [B]whole words
Here’s my code so far:
[CODE]function doHighlight(bodyText, searchTerm, highlightStartTag, highlightEndTag)
{
// the highlightStartTag and highlightEndTag parameters are optional
if (searchTerm == ”)
{
return bodyText;
}
else
{
if ((!highlightStartTag) || (!highlightEndTag)) {
highlightStartTag = “<font style=’color:blue; background-color:yellow;’>”;
highlightEndTag = “</font>”;
}
// find all occurences of the search term in the given text,
// and add some “highlight” tags to them (we’re not using a
// regular expression search, because we want to filter out
// matches that occur within HTML tags, script blocks, and
// html entities, so we have to do a little extra validation)
var newText = “”;
var i = -1;
var lcSearchTerm = searchTerm.toLowerCase();
var lcBodyText = bodyText.toLowerCase();
while (bodyText.length > 0) {
i = lcBodyText.indexOf(lcSearchTerm, i+1);
if (i < 0) {
newText += bodyText;
bodyText = “”;
} else {
// skip anything inside an HTML tag
if (bodyText.lastIndexOf(“>”, i) >= bodyText.lastIndexOf(“<“, i)) {
// skip anything inside a <script> block
if (lcBodyText.lastIndexOf(“/script>”, i) >= lcBodyText.lastIndexOf(“<script”, i)) {
//skip anything inside an &…; html symbol block
if (lcBodyText.lastIndexOf(“;”, i) >= lcBodyText.lastIndexOf(“&”, i)) {
newText += bodyText.substring(0, i) + highlightStartTag + bodyText.substr(i, searchTerm.length) + highlightEndTag;
bodyText = bodyText.substr(i + searchTerm.length);
lcBodyText = bodyText.toLowerCase();
i = -1;
}
}
}
}
}
return newText;
}
}
I am planning to wrap this code with a wrapper that will allow one to pass it an id so the highlighting will only occur in the desired DOM elements. It looks really bad with the term occurs in your website’s menu and is therefore highlighted!
Terry