SearchSearch   MemberlistMembers   RegisterRegister   ProfileProfile   Log inLog in 

Highlighting Search Keywords in ASP

 
Post new topic   Reply to topic    Open Hosting Internet Solutions Forum Index -> Articles and Tutorials -> Server Side Web Development
View previous topic :: View next topic  
Author Message
Nick
Forum Moderator


Joined: 18 Jun 2002
Posts: 3635

PostPosted: Wed Mar 08, 2006 2:43 pm    Post subject: Highlighting Search Keywords in ASP Reply with quote

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"))
%>
Back to top
View user's profile Send private message Visit poster's website MSN Messenger
Display posts from previous:   
Post new topic   Reply to topic    Open Hosting Internet Solutions Forum Index -> Articles and Tutorials -> Server Side Web Development All times are GMT
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum


Powered by phpBB 2.0.11 © 2001, 2002 phpBB Group
FAQClick here for help using the phpBB forum