I'm trying to highlight the result of a search within some text. I have written an extension method:
public static string Highlight(this HtmlHelper html, string input, string searchPhrase)
{
Regex.Replace(input,
"\\b" + searchPhrase + "\\b",
"<strong>" + searchPhrase + "</strong>",
RegexOptions.IgnoreCase);
}
But obvisouly when this is Html.Encoded from the view, the html tags are just rendered as part of the text.
Is there a better way of doing this? Or if my idea is ok, how do I make it work?
public static MvcHtmlString Highlight(this HtmlHelper html, string input, string searchPhrase)
{
var value = Regex.Replace(
input,
"\\b" + searchPhrase + "\\b",
"<strong>" + searchPhrase + "</strong>",
RegexOptions.IgnoreCase
);
return MvcHtmlString.Create(value);
}
and in the view:
@Html.Highlight("foo", "f")