Reputation: 389
I have an MVC application wherein I have a string that gets created dynamically from the view model using C# code, there are certain words that need to be marked in bold. For instance, if the string created from C# code is 'This is a test', I wish to display the word 'test' as bold when it is passed from the view model to the cshtml view and is displayed on screen, I tried Regex.replace, which helped me get the text wrapped in bold tags, but after that what I saw on screen was plain text with tags 'This is a < b >test< /b >, while I expected it to be - 'This is a test'. I tried Regex.replace, but that didn't work. Can someone please suggest what should be done in this case ? Below is my code:
content = System.Text.RegularExpressions.Regex.Replace(content, wordToHighlight, "<b>" + wordToHighlight + "</b>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
Upvotes: 0
Views: 1870
Reputation: 8302
In your case:
using System;
using System.Text.RegularExpressions;
public class Program
{
public static void Main()
{
String term = "test";
String input = "This is a test";
String result = Regex.Replace( input, String.Join("|", term.Split(' ')), @"<b>$&</b>");
Console.Out.WriteLine(result);
}
}
would give you: This is a <b>test</b>
In order to display this string in your View, use:
@Html.Raw(result)
which will display your string as: This is a test
Upvotes: 2