Today, I encountered a problem: how to highlight case-insensitive keywords in a web page. For example: text abcaBcabCaBCabcaBCa, keyword bc, in case of case-insensitivity, there are a total of 6 matches.
Then what is displayed on the web page is abcaBcabCaBCabcaBCa.
Many people think of the replace function. The prototype is
Replace(string,find,replacewith[,start[,count[,compare]]])
string required, string expression, containing the substring to be replaced
find required option, the substring being searched
replacewith is required, the substring used for replacement
start optional, the position to start searching for substrings, the default is 1
count optional, the number of substring replacements to perform, the default is -1, indicating all possible replacements
compare optional, comparison mode, 0: binary comparison; 1: text comparison
Although the last parameter can solve the case insensitivity problem, what should be replaced?
Because from the example, bc, Bc, bC, and BC have all been searched, but they cannot be uniformly replaced with one text.
So, use the Instr function to help us.
Search from the source string, left to right, each time a match is found. Just follow the three steps
1. Output the string to the left of the matching item
2. Apply the matching item to the style <span> and output it
3. Repeat the previous two steps and continue to search for the string on the right until the end of the search
The code is as follows:
Copy the code code as follows:
public function HighLight(S,F)
dim tL,tM,tR,k
tL=
tM=
tR=S
k=instr(1,tR,F,1)
do while k>0
tL=tL & left(tR,k-1)
tM=mid(tR,k,len(F))
tL=tL & <span style='color:red'> & tM & </span>
tR=right(tR,Len(tR)-len(F)-k+1)
k=instr(1,tR,F,1)
loop
HighLight=tL & tR
end function
When calling, the code is as follows:
Copy the code code as follows:
tS=abcaBcabCaBCabcaBCa
tF=bc
response.Write(tS)
response.Write(<br/>)
response.Write(HighLight(tS,tF))
In this way, the example at the beginning looks like
On the other hand, thinking about whether it is more convenient to use regular expressions? Tried several times with no result. Let’s see which expert uses regular rules to solve this problem.
After writing the article, netizen Yugong gave a solution to the regular expression. Tested and found to be correct. Now his code is pasted below. Thank you very much to him.
code
Copy the code code as follows:
Function HighLight(S,F)
Dim regEx
Set regEx = New RegExp
regEx.IgnoreCase = True
regEx.Global = True
regEx.Pattern = ( & F & )
HighLight = regEx.Replace(S,<span style='color:red'>$1</span>)
End Function
Response.write HighLight(abcaBcabCaBCabcaBCa,bc)