Highlighting Search Keywords in ASP

Written by Nick Dunn published 8th Mar 2006 | Comment on this article

Highlight occurance of a string within another string. Very useful for displaying matching keywords in database search results.

Highlighting Search Keywords in ASP

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.

<%
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:

searchPage.asp?search=word

The function is therefore called using the following syntax.

<%
Response.Write stringReplace("This is a very useful script for displaying highlighted search keywords.",Request.QueryString("search"))
%>