Re: Highlighting keywords in search results [message #23623 is a reply to message #23603] |
Thu, 24 March 2005 11:05 |
|
naudefj
Messages: 3771 Registered: December 2004
Karma:
|
Senior Member Administrator Core Developer |
|
|
Here is the initial code that needs to be added to lib.js. Please let me know if this is what you had in mind, and if we need to add/consider anything else.
The following is still missing:
- Differentiate between words and phrases (it currently breaks everything up into words)
- Use different colors for different words/phrases
- Color definitions must go to the CSS template
I will complete the code sometime next week (just don't have enough time right now).
/* Wrapper function - split search text into separate phrases and words */
function highlightSearchTerms(searchText)
{
if (!document.body || typeof(document.body.innerHTML) == "undefined") return false;
if ( typeof(searchText) == "undefined") {
searchText = getParameter("srch");
// alert("Search String = [" + searchText + "]");
}
var bodyText = document.body.innerHTML;
var searchArray = searchText.split(" ");
for (var i = 0; i < searchArray.length; i++) {
// alert("Highlight word = [" + searchArray[i] + "]");
bodyText = doHighlight(bodyText, searchArray[i]);
}
document.body.innerHTML = bodyText;
return true;
}
/* Highlights a text string by adding HTML tags before and after the search term. */
function doHighlight(bodyText, searchTerm)
{
const highlightStartTag = "<font style='background-color:yellow;'>";
const highlightEndTag = "</font>";
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)) {
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;
}
/* Get URL parameter */
function getParameter(paramName) {
var currentUrl = window.location.search;
var strBegin = currentUrl.indexOf(paramName) + (paramName.length+1);
var strEnd = currentUrl.indexOf("&",strBegin);
if (strEnd==-1) strEnd = currentUrl.length;
var paramValue = unescape( currentUrl.substring(strBegin,strEnd) );
while (paramValue.indexOf("+") > 1 ) paramValue = paramValue.replace("+", " ");
return paramValue;
}
To start highlighting, use
<body onload="highlightSearchTerms("word1 word2");">
or ...
<body onload="highlightSearchTerms();">
with URL parameter: ...&srch=word1+word2
Best regards.
Frank
|
|
|