Highlight Search Results
Some search engines highlight the words that you searched for when they display their results. I have recently had a need to do this and rather than use someone elses code I thought I’d write my own.
It’s written in Visual Basic as a function but could quite easily be used in it’s own class for reuse through out your application.
You will also need to add some CSS to your stylesheet.
.highlight
{
background-color: Yellow;
font-weight: bold;
}
Public Function highlight(ByVal result As String, ByVal searchTerm As String) As String
Dim currentPosition As Integer
Dim indexPosition As Integer
Dim startHighlight As String = "<span class=""highlight"">"
Dim endHighlight As String = "</span>"
If result.ToUpper.Contains(searchTerm.ToUpper) Then
While currentPosition + searchTerm.Length < result.Length - 1
If result.ToUpper.Substring(currentPosition, result.Length - currentPosition).Contains(searchTerm.ToUpper) Then
indexPosition = result.ToUpper.IndexOf(searchTerm.ToUpper, currentPosition)
result = result.Insert(indexPosition, startHighlight)
indexPosition = indexPosition + searchTerm.Length + startHighlight.Length
result = result.Insert(indexPosition, endHighlight)
currentPosition = indexPosition + searchTerm.Length + endHighlight.Length
Else
currentPosition = result.Length
End If
End While
End If
Return result
End Function








Nice piece of vb code - bookmarked!