Forum Moderators: open
<%
Function Bold(strInput, strSearch)
Dim istart
Dim iend
Dim icur
Dim strOutput
dim intLen
strOutput = strInput
intLen = Len(strSearch)
icur = 1
istart = InStr(icur, strOutput, strSearch, 1)
Do While istart
strOutput = Left(strOutput, istart - 1) & "<b>" & Mid(strOutput, istart, intLen) & "</b>" _
& Mid(strOutput, istart + intLen)
icur = istart + intLen + 7
istart = InStr(icur, strOutput, strSearch, 1)
Loop
Bold = strOutput
End Function
Dim strInput
strInput = "would find and replace Donnie Darkowith its "
strInput = strInput & "bold equivalent, as well as DONNIE DARKOWITH etc."
Call Response.Write("Before: " & strInput & "<br />")
Call Response.Write("After: " & Bold(strInput, "Donnie Darkowith"))
%>
If you wanted to allow only case sensitive replacements, you could just do:
strInput.Replace(strSearch, "<b>" & strSearch & "</b>")
Regex.Replace(strInput, strSearch, "<b>$&</b>", RegexOptions.IgnoreCase)
This expression says find strSearch in strInput. Then replace it with <b>the search string</b>. The $& is the regular expression code to say the search string. The option RegexOptions.IgnoreCase says to do a case insensitive comparison.
The regular expression parser in the .NET framework is incredibly powerful.
Actually, classic Asp already has a function that works more or less like String.Replace in VB.NET
This invaluable function is called Replace and in it's most basic form it takes three parameters:
plainString = "Donnie Darko bla bla bla donnie darko" boldString = Replace(plainString, "Donnie Darko", "<b>Donnie Darko</b>") This changes all occurrences of Donnie Darko in the string plainString to <b>Donnie Darko</b> and stores the new string as boldString.
Unfortunately, this is case sensitive... but we can solve that by using the optional parameters supplied in the Replace function:
plainString = "Donnie Darko bla bla bla donnie darko" boldString = Replace(plainString, "Donnie Darko", "<b>Donnie Darko</b>", 1, -1, vbTextCompare) Voilá, one line of code.
The first 1 is the Start parameter. It specifies what position (from left) in the string you want the search to start from. In this case, we don't want to skip anything, so the function will start from the first character.
The second parameter (-1 here) is the Count parameter and specifies how many times to replace the substring. The value -1 means the function will replace ALL occurrences in the string. If, for some reason, you only want to replace the first 4 "Donnie Darko" with "<b>Donnie Darko</b", you set this to 4 etc.
The last parameter is the Compare parameter. The default value for this is vbBinaryCompare meaning the replace will be case sensitive. If we want the function to ignore case, we have to use vbTextCompare instead.
Hope this helped.
//ZS
Xoc - I'm pretty certain the constant is defined automatically in VBScript... Try creating a simple webpage:
<%
Const vbTextCompare = 1
%> It'll give you a "Name redefined" error.
//ZS