Search code examples
c#.netasp.netsearchhighlighting

Search keyword highlight in ASP.Net


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 a span or similar. I am looking for an efficient function to do this.

E.g.

Keywords: "lorem ipsum"

Result: "Some text containing lorem and ipsum"

Desired HTML output: "Some text containing <span class="hit">lorem</span> and <span class="hit">ipsum</span>"

My results are case insensitive.


Solution

  • 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("<span class=\"hit\">{0}</span>", "$0"), RegexOptions.IgnoreCase);
            }
            catch
            {
                //
            }
        }
        return input;
    }
    

    Any further suggestions or comments?