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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With