Search and Replace by Meraj SamiThis one came about helping one of the users on one of the message board. He had asearch page from which the users on his site, guess what, could do the search. He wantedto highlight the search criteria in his result from the database. For example if theuser's search string was "the" and one of the string in the search resultcontained (remember, it is an example) "whatever summer winter tHe weather whetherTHE the The tHe thE thermometer thermometerthe", every occurrence of "the"should be highlighted. If you do it with replace function, for example, | <% searchString="the" replaceWith="<FONT COLOR='red'><b>" & searchString & "</b></font>" strOriginal="whatever summer winter tHe weather whether THE the The tHe thE thermometer thermometerthe" strOriginal=Replace(strOriginal,searchString,replaceWith,1,-1,1) %> then you can highlight every occurrence of the search string in the result, but in the process lose the case of the search string -- all the occurrence of "the" now will be in lower case. To avoid that I came up with this little function that will highlight all the occurrence of the search string in the result and also maintain the original case. | | <SCRIPT LANGUAGE="VBSCRIPT" RUNAT="SERVER"> Function stringReplace(strSearchWithin,strSearchFor) Dim lngStartingPosition Dim lngFoundPosition Dim strReplaced 'Set the start position lngStartingPosition=1 lngFoundPosition=InStr(lngStartingPosition,strSearchWithin,strSearchFor,1) do while lngFoundPosition > 0 'found strReplaced=strReplaced & Mid(strSearchWithin,lngStartingPosition,lngFoundPosition-lngStartingPosition) & "<font color='red'>" & mid(strSearchWithin,lngFoundPosition,len(strSearchFor)) & "</font>" lngStartingPosition=lngFoundPosition+len(strSearchFor) lngFoundPosition=InStr(lngStartingPosition,strSearchWithin,strSearchFor,1) Loop stringReplace=strReplaced & Mid(strSearchWithin,lngStartingPosition) 'catch the last one End Function </SCRIPT> <% OPTION EXPLICIT Dim strSearchWithin,strSearchFor strSearchWithin="whatever summer winter tHe weather whether THE the The tHe thE thermometer thermometerthe" strSearchFor="the" Response.Write stringReplace(strSearchWithin,strSearchFor) %> | |