1 Star2 Stars3 Stars4 Stars5 Stars
Loading ... Loading ...
Email Email

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

Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google

About the Author

Nick

I'm Nick Allport, Web Developer out of South Wales, UK. These are my Ramblings, Thoughts and Stuff about all sorts of things. See what I did there?

One Response to “ Highlight Search Results ”

  1. Nice piece of vb code - bookmarked!

Leave a Reply

You can use these XHTML tags: <a href="" title=""> <abbr title=""> <acronym title=""> <blockquote cite=""> <code> <em> <strong>