Ian Obermiller

Part time hacker, full time dad.

Highlight search terms in C#, Javascript and TypeScript

Posted

Following is a function that given a string and a search query will wrap bold tags around search terms that were found in the query:

Example:

text = "The theory of the big bang was proposed in..."
query = "Big Bang Theory"
result = "The <b>theory</b> of the <b>big</b> <b>bang</b> was proposed in..."
rendered = The theory of the big bang was proposed in....

C# Version

(note: you may want to return an HtmlString instead to make it easier to call from a view.)

string HighlightSearchTerms(string text, string query)
{
    var terms = query.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries).Select(s => s.Replace("|", "\\|"));
    var regex = new Regex("(" + string.Join("|", terms) + ")", RegexOptions.IgnoreCase);
    return regex.Replace(text, "<b>${0}</b>");
}

Javascript

function highlightSearchTerms(text, query) {
  var terms = query.split(' ').map(function (s) {
    return s.replace('|', '\\|');
  });
  var regex = new RegExp('(' + terms.join('|') + ')', 'gi');
  return text.replace(regex, '<b>$&</b>');
}

TypeScript

(just the JS version with type annotations)

function highlightSearchTerms(
  text: string,
  query: string,
): string {
  var terms = query.split(' ').map(function (s) {
    return s.replace('|', '\\|');
  });
  var regex = new RegExp('(' + terms.join('|') + ')', 'gi');
  return text.replace(regex, '<b>$&</b>');
}