ASP 中的关键字高亮显示





5.00/5 (1投票)
2000 年 6 月 16 日

142181
一个简单的函数,用于在 ASP 中高亮显示关键字。
引言
在编写我的留言板 ASP 脚本版本时,我发现需要一个能够高亮消息文本中某些关键字的函数。
我的第一个想法是使用 VBScript 内置的 Replace()
函数。使用 Replace 的唯一问题是,我无法保留文本中字母的原始大小写。请考虑以下示例
myText = "Using Replace function to make word REPLACE bold." myText = Replace(myText, "replace", "<b>replace</b>", 1, -1, 1)
生成的字符串将是 “使用 <b>replace</b> 函数使单词 <b>replace</b> 加粗。”。它确实使所有单词“Replace”加粗,但也更改了这些单词的大小写。
这就是为什么我不得不编写这个小 Highlight
函数的原因。这个函数没有什么特别之处,但它完成了我需要的功能,我希望你也能在你的 ASP 脚本中使用它。所以它如下所示
'***************************************************************************** ' HIGHLIGHT function will search text for a specific string ' When string is found it will be surrounded by supplied strings ' ' NOTE: Unfortunately Replace() function does not preserve the original case ' of the found string. This function does. ' ' Parameters: ' strText - string to search in ' strFind - string to look for ' strBefore - string to insert before the strFind ' strAfter - string to insert after the strFind ' ' Example: ' This will make all the instances of the word "the" bold ' ' Response.Write Highlight(strSomeText, "the", "<b>", "</b>") ' Function Highlight(strText, strFind, strBefore, strAfter) Dim nPos Dim nLen Dim nLenAll nLen = Len(strFind) nLenAll = nLen + Len(strBefore) + Len(strAfter) + 1 Highlight = strText If nLen > 0 And Len(Highlight) > 0 Then nPos = InStr(1, Highlight, strFind, 1) Do While nPos > 0 Highlight = Left(Highlight, nPos - 1) & _ strBefore & Mid(Highlight, nPos, nLen) & strAfter & _ Mid(Highlight, nPos + nLen) nPos = InStr(nPos + nLenAll, Highlight, strFind, 1) Loop End If End Function '********************************************************************************
要使用此函数 - 将其包含在你的 ASP 脚本中,并像这样调用它
Response.Write Highlight(myText, "someword", "<font color=red>", "</font>")