Jump to content

Search String In VBScript


Recommended Posts

I want to search a string and display any matches with the search word in a web page. Now using the Replace function will not do as it will replace the word but not keep the original word in the text, i.e., if search word is fear and the match in the string is Fear, it will change the punctuation from cap to lower and visa versa. So I created some code to find where the match(es) occur and replace the original word with formated html code around the matched word to have it appear highlighted. The problem is that fear will match fearless, much like the find function in Word for example. If I add a space before and after the search word, well that almost works. But does not allow for puctuation after the search word or if the search word is the first word in the string. So anybody know how to do this?Here is the code I worked out so far (You can run it in a web page for test purposes, although I intend to use in asp).<code><html><head><title>test search</title><body bgcolor="ffffff" text="000000"> <script language=vbscript><!--' Mid(string, start[, length])' Left(string, length)' Right(string, length)' InStr([start, ]string1, string2[, compare])' string2 is not found = 0' start > Len(string2)= 0MyString = "The quick brown dog jumps over the other ""dogs"". A Dog or Dogs will do that from time to time. My Dog will not though. Of course in you are dogless, well..." VarWord = "dog"document.write "MyString = " & MyString & "<br />"document.write "VarWord = " & VarWord & "<br />" & "<br />" & "<br />"document.write "_________________________________________" & "<br />" & "<br />" & "<br />"MyNumber = 1MyVarNum = Len(VarWord)' This pulls out the first part of the string and first match and the formated web page codeMyNumber = InStr(MyNumber,MyString,VarWord,1)MyStr = Mid(MyString, 1, MyNumber-1) & "<font color=red><b><u>" & Mid(MyString, MyNumber ,len(VarWord)) & "</u></b></font>"MyNum2 = MyNumberDo MyNumber = InStr((MyNum2 + 1),MyString,VarWord,1)' This pulls out the last part of the string if the is only one match and skips to the "elseif"' if there is more than one match.If MyNumber = 0 ThenMyStr = MyStr & Right(MyString, Len(MyString) - ((MyNum2 + MyVarNum) - 1)) & "<br />"Exit Do' This pulls out subsequient matches in the stringElseIf MyNumber > 1 ThenMyStr = MyStr & Mid(MyString, MyNum2 + Len(VarWord), MyNumber - (Len(VarWord)) - MyNum2) & "<font color=red><b><u>" & Mid(MyString, MyNumber ,len(VarWord)) & "</u></b></font>"MyNum2 = MyNumberEnd IfLoop document.write MyStr--></script></body></html></code>

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Create New...