Nick Forum Moderator

Joined: 18 Jun 2002 Posts: 3635
|
Posted: Wed Mar 08, 2006 2:43 pm Post subject: Highlighting Search Keywords in ASP |
|
|
Highlighting Search Keywords in ASP
Highlight occurance of a string within another string. Very useful for displaying matching keywords in database search results.
After creating a basic site search I wanted to highlight the occurance of the search keywords in the results displayed.
The normal Replace function in ASP is not sufficient because it is case sensitive and is really unsatisfactory. I've adapted some code into a reusable function that can be used on a search page.
| Code: | <%
Function stringReplace(strSearchWithin,strSearchFor)
If Len(strSearchWithin) > 0 And Len(strSearchFor) > 0 Then
intStart = 1
intFound = InStr(intStart,strSearchWithin,strSearchFor,1)
Do While intFound > 0
strReplaced = strReplaced & Mid(strSearchWithin,intStart,intFound - intStart) & "<span style='background-color:yellow'>" & mid(strSearchWithin,intFound,len(strSearchFor)) & "</span>"
intStart = intFound + len(strSearchFor)
intFound = InStr(intStart,strSearchWithin,strSearchFor,1)
Loop
stringReplace = strReplaced & Mid(strSearchWithin,intStart)
Else
stringReplace = strSearchWithin
End If
End Function
%> |
The matching string to be highlighted is passed to the page using a querystring parameter "search", for example:
| Code: | | searchPage.asp?search=word |
The function is therefore called using the following syntax.
| Code: | <%
Response.Write stringReplace("This is a very useful script for displaying highlighted search keywords.",Request.QueryString("search"))
%> |
|
|