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) =>
                                   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: 42245


- 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

Gavan McGregor 09/10/2015 13:45
In response to Downloading multiple files in ASP.NET
Hi, (long time reader, first time poster!) Although it's a deliberately simple example, It's /...

Rodrigo 08/10/2015 20:40
In response to MVC 5 with EF 6 in Visual Basic - Creating an Entity Framework Data Model

Warren Caulton 08/10/2015 20:18
In response to Solved - The Microsoft.ACE.OLEDB.12.0 provider is not registered on the local machine
I have a Web Page that uploads and parses through an excel file to upload the latest sheets data to...

Vaclav Elias 07/10/2015 17:26
In response to ASP.NET 5: Dependency Injection and Services in MVC
Hi Mike, this is very nicely explained and elaborated from non dependency to dependency on real I am...

Nizen 07/10/2015 15:07
In response to Bind Data From a SqlDataSource to a Label
Wow thank you very much! I was really stuck and now I can be able to proceed coding as a result of...

Manolo 06/10/2015 21:15
In response to ASP.NET MVC Uploading and Downloading Files
Muchas gracias por esta información, Felicitaciones por su trabajo , me ayudó mucho , Saludos desde...

adam 05/10/2015 14:35
In response to Integrating Web API with ASP.NET Razor Web Pages
Can you re-open this web api project in webmatrix, once you've added web api? Basically I'm looking...

nish 24/09/2015 18:48
In response to Managing Checkboxes And Radios In ASP.NET Razor Web Pages
Very Interresting stuff! it really helped me to send an int value by checking a checkbox!...

Uğur Dinç 24/09/2015 16:45
In response to Scheduled Tasks In ASP.NET With Quartz.Net
Simplest and best explanation on Quartz.NET. Thank you!...

woo 24/09/2015 15:34
In response to Implementing Google's EU End User Consent Policy
Is there any way for the banner to appear only to EU visitors? I am referring to the jQuery code...