Highlighting Keywords Found In Search Results

4.64 (14 votes)

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) =>
                                   string.Format("<span style=\"background-color:{0}\">{1}</span>", 
  return words.Select(word => "\\b" + word.Trim() + "\\b")
              .Aggregate(text,(current, pattern) => 
                          string.Format("<span style=\"background-color:{0}\">{1}</span>", 


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:

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

Date Posted:
Last Updated:
Posted by:
Total Views to date: 43056


- anooj

Nice,,,,It's very useful.

- dimitris

Very nice, solid implementation. Came in handy thank you very much.

- Atit


The solution provided to highlight the terms on web page works okay for single terms. But it is not working if there is a space between the terms.

e.g. searches fine if "companies" is the input
but doesn't work if "companies act" is the input

- kishor

it will give an error if I give a single ( or ) as a keyword

- leo

Hi there,

do you think it would be possible to improve this code for matching provided keywords ignoring accented letters?
for examples if I specify "coupe" as my keyword and I'd like to match coupé in a phrase contains "coupé".

Do you think it would be possible?
I can't find an elegant way.


- Mike


Thre's a solution to that in: this Stackoverflow post

- Irfan Khan

This is truely helpful. Thank you for the brilliant tip.

- Péter Fuchs

Great Solution. Thx

I get the following Exception: "System.ArgumentNullException: Value cannot be null. Parameter name: input"

I changed your string empty check like this:
if (String.IsNullOrEmpty(text) || String.IsNullOrEmpty(keywords) || String.IsNullOrEmpty(cssClass))
return text;

Recent Comments

Phil 29/11/2015 18:48
In response to iTextSharp - Working with images
Hi Mike, great article as ever. Any chance you can do an example of adding a swf to a pdf with I it...

makhlas 27/11/2015 17:05
In response to How To Send Email In ASP.NET MVC
hello, thanks for sharing these tutos , but when i apply the send button, i'm gettin this error...

raphael 27/11/2015 13:59
In response to ASP.NET 5: Managing Client-side Dependencies with NPM, Bower and Gulp
i fixed it. i'm not sure *what* it is that VS does, but you get the same result if you do a "npm on...

Raphael 27/11/2015 13:02
In response to ASP.NET 5: Managing Client-side Dependencies with NPM, Bower and Gulp
There seems to be a major issue with the dependency manager in VS2015. I haven't yet figured out but...

Joaquín Bresan 26/11/2015 17:58
In response to Getting the identity of the most recently added record
Great contribution friend. Thank you so much for sharing....

JR 26/11/2015 02:49
In response to ASP.NET MVC 5 with EF 6 - Working With Files
Hello, Where is the location of the database? Thanks...

sumalatha 24/11/2015 22:09
In response to ASP.NET 5 Middleware, Or Where Has My HttpModule Gone?
Great article. I have gone through hundreds of articles, finally this gives the comprehensive of...

TimPat10 24/11/2015 17:35
In response to A Better Way To Export Gridviews To Excel
Great article. I've noticed that date fields have to be re-formatted when the spreadsheet is pulled...

Rajasekar 24/11/2015 12:27
In response to Import Data From Excel to Access with ASP.NET
While use this code i'm facing on error: "Unrecognized Database format C:\mydabase.accdb" can any...

Parmod 24/11/2015 07:28
In response to ASP.NET 5 Project Basics
For a new learner (Fresher) in ASP.NET there is a issue Fresher have to learn two types of , old...