搜索关键字变色及高亮显示

1.替换关键字,对字体变色。
        public static string ReplaceRed(string strtitle, string redkey)
        
{
            
if (redkey == "" || redkey == null)
            
{
                
return strtitle;
            }

            
else
                strtitle 
= strtitle.Replace(redkey, " <font color='#ff0000'>" + redkey + " </font>");
            
return strtitle;
        }

2.用正则,CSS背景变色。
        protected string HighlightText(string inputText,string searchWord)
        
{
            System.Text.RegularExpressions.Regex expression 
= new System.Text.RegularExpressions.Regex(searchWord.Replace(" ""|"), System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            
return expression.Replace(inputText,new System.Text.RegularExpressions.MatchEvaluator(ReplaceKeywords));
        }

        
public string ReplaceKeywords(System.Text.RegularExpressions.Match m)
        
{
            
return "<span class='highlightTxtSearch'>" + m.Value + "</span>";
        }

CSS:
.highlightTxtSearch
{
    background-color
:Yellow;
}
原文地址:https://www.cnblogs.com/cnaspnet/p/1230882.html