I'm trying to create/modify a script that highlights certain words on a page, and changes them into links. So if I had a page about dogs, each occurrence of the word 'dog' will be automatically turned into a link.
So far I've got it working, but it's overwriting any links that are already hard coded into the page. I need the script to ignore anything inside < >, such as links, bold, etc...
Any ideas?
- Code: Select all
<script language=JavaScript>
function doHighlight(bodyText, searchTerm)
{
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 {
newText += bodyText.substring(0, i) + "<a href=\"http://www.domain.com/search.php?s=" + bodyText.substr(i, searchTerm.length) + "\">" + bodyText.substr(i, searchTerm.length) + "</a>";
bodyText = bodyText.substr(i + searchTerm.length);
lcBodyText = bodyText.toLowerCase();
i = -1;
}
}
return newText;
}
function highlightSearchTerms(searchText)
{
searchArray = searchText.split(" ");
var bodyText = document.body.innerHTML;
for (var i = 0; i < searchArray.length; i++) {
bodyText = doHighlight(bodyText, searchArray[i]);
}
document.body.innerHTML = bodyText;
return true;
}
</script>
<body>
The dog chased the cat into the <a href="#">dog house</a>
</body>
<script language=JavaScript>
highlightSearchTerms('cat dog');
</script>