Search keyword highlight in ASP.Net

后端 未结 4 480
悲哀的现实
悲哀的现实 2021-02-04 17:23

I am outputting a list of search results for a given string of keywords, and I want any matching keywords in my search results to be highlighted. Each word should be wrapped in

4条回答
  •  Happy的楠姐
    2021-02-04 17:50

    Here's what I've decided on. An extension function that I can call on the relevant strings within my page / section of my page:

    public static string HighlightKeywords(this string input, string keywords)
    {
        if (input == string.Empty || keywords == string.Empty)
        {
            return input;
        }
    
        string[] sKeywords = keywords.Split(' ');
        foreach (string sKeyword in sKeywords)
        {
            try
            {
                input = Regex.Replace(input, sKeyword, string.Format("{0}", "$0"), RegexOptions.IgnoreCase);
            }
            catch
            {
                //
            }
        }
        return input;
    }
    

    Any further suggestions or comments?

提交回复
热议问题