Highlighting Keywords Found In Search Results

A common question in the forums is how to highlight key words found in search results. Here's an extension method that does that, both for partial matches, or whole word matches.


/// <summary>
/// Wraps matched strings in HTML span elements styled with a background-color
/// </summary>
/// <param name="text"></param>
/// <param name="keywords">Comma-separated list of strings to be highlighted</param>
/// <param name="cssClass">The Css color to apply</param>
/// <param name="fullMatch">false for returning all matches, true for whole word matches only</param>
/// <returns>string</returns>
public static string HighlightKeyWords(this string text, string keywords, string cssClass, bool fullMatch)
{
  if (text == String.Empty || keywords == String.Empty || cssClass == String.Empty)
    return text;
  var words = keywords.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
  if (!fullMatch)
    return words.Select(word => word.Trim()).Aggregate(text,
                 (current, pattern) =>
                 Regex.Replace(current, 
                                 pattern,
                                   string.Format("<span style=\"background-color:{0}\">{1}</span>", 
                                   cssClass, 
                                   "$0"),
                                   RegexOptions.IgnoreCase));
  return words.Select(word => "\\b" + word.Trim() + "\\b")
              .Aggregate(text,(current, pattern) => 
                        Regex.Replace(current, 
                        pattern,
                          string.Format("<span style=\"background-color:{0}\">{1}</span>", 
                          cssClass, 
                          "$0"),                                           
                          RegexOptions.IgnoreCase));

}

The method uses Regex, so when you add it to a class, make sure you reference System.Text.RegularExpressions. As you can see, it applies a background colour to a span, so a valid CSS colour needs to be passed in. I haven't added any validation to the method to check for a valid colour, but it wouldn't be too difficult to do. For Hex colours, the test would be 6 characters, numbers (0-9) or letters (a-f). RGB colours are composed of 3 sets of numbers between 0 and 255. And there is a finite list of 16 HTML colour names, although you might want to accept SVGA colour names too, which are supported by most browsers. More details on colours can be found here. Alternatively, you can alter the html that this method produces so that the argument can be CSS class name rather than a colour.

As it is, here's how to use it within MVC where I shall pass in the following to the View:


ViewData["temp"] = "aster faster plaster mastering forecaster.";

Within the View itself, using the full word matches option:


<div><%= ViewData["temp"].ToString().HighlightKeyWords("aster", "yellow", true)%></div>


which results in the following:

Changing true to false results nicely in this:

Using the method in Web Forms is easy too. Assuming that a search result has been passed to a DataBound control with an ItemTemplate, here's how it might look:


<ItemTemplate>
   <asp:Label ID="Label1" runat="server" Text='<%# Eval("mySearchResult").ToString().HighlightKeyWords("aster", "yellow", true) %>' />
</ItemTemplate>