0

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?

1 Answer 1

3
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")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.