Hi nauna,
Check this example. Now please take its reference and correct your code.
HTML
<asp:TextBox runat="server" ID="txtSearch" Text="paragraph one" />
<asp:Button Text="Highlight" runat="server" OnClick="OnHighlight" />
Namespaces
C#
using System.Linq;
using System.Text.RegularExpressions;
VB.Net
Imports System.Linq
Imports System.Text.RegularExpressions
Code
C#
public string HighlightKeyWords(string text, string keywords, string cssClass, bool fullMatch)
{
if (text == String.Empty || keywords == String.Empty || cssClass == String.Empty)
return text;
var words = keywords.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
if (!fullMatch)
{
return words.Select(word => word.Trim()).Aggregate(text,
(current, pattern) =>
Regex.Replace(current, pattern,
string.Format("<div><span style=\"background-color:{0}\">{1}</span></div>", cssClass, "$0"),
RegexOptions.IgnoreCase));
}
else
{
return words.Select(word => "\\b" + word.Trim() + "\\b")
.Aggregate(text, (current, pattern) =>
Regex.Replace(current, pattern,
string.Format("<div><span style=\"background-color:{0}\">{1}</span><div>", cssClass, "$0"),
RegexOptions.IgnoreCase));
}
}
protected void OnHighlight(object sender, EventArgs e)
{
string val = "This is paragraph one topic one to add the custom tags.";
Response.Write(HighlightKeyWords(val, txtSearch.Text.Trim(), "yellow", true));
}
VB.Net
Public Function HighlightKeyWords(ByVal text As String, ByVal keywords As String, ByVal cssClass As String, ByVal fullMatch As Boolean) As String
If text = String.Empty OrElse keywords = String.Empty OrElse cssClass = String.Empty Then Return text
Dim words = keywords.Split({","c}, StringSplitOptions.RemoveEmptyEntries)
If Not fullMatch Then
Return words.Select(Function(word) word.Trim()) _
.Aggregate(text, Function(current, pattern) _
Regex.Replace(current, pattern,
String.Format("<div><span style=""background-color:{0}"">{1}</span></div>", cssClass, "$0"),
RegexOptions.IgnoreCase))
Else
Return words.Select(Function(word) "\b" & word.Trim() & "\b") _
.Aggregate(text, Function(current, pattern) _
Regex.Replace(current, pattern,
String.Format("<div><span style=""background-color:{0}"">{1}</span><div>", cssClass, "$0"),
RegexOptions.IgnoreCase))
End If
End Function
Protected Sub OnHighlight(ByVal sender As Object, ByVal e As EventArgs)
Dim val As String = "This is paragraph one topic one to add the custom tags."
Response.Write(HighlightKeyWords(val, txtSearch.Text.Trim(), "yellow", True))
End Sub
Screenshot