I am working on creating blazor page that display search box to search from list , i want the matching string not the whole word to be highlighted if it match the input in search box the result now is
<mark>ap</mark>
and here is the code :
@page "/test"
@using System.Linq
<input type="text" @bind-value="@searchTerm" @bind-value:event="oninput" placeholder="Search" />
<ul>
@foreach (var item in filteredItems)
{
<li>@GetHighlightedText(item)</li>
}
</ul>
@code {
private string searchTerm = "";
private List<string> items = new List<string> { "apple", "banana", "cherry", "date", "elderberry" };
private List<string> filteredItems
{
get
{
if (string.IsNullOrWhiteSpace(searchTerm))
{
return items;
}
else
{
return items.Where(item => item.Contains(searchTerm, StringComparison.OrdinalIgnoreCase)).ToList();
}
}
}
private string GetHighlightedText(string text)
{
if (string.IsNullOrWhiteSpace(searchTerm))
{
return text;
}
int index = text.IndexOf(searchTerm, StringComparison.OrdinalIgnoreCase);
if (index < 0)
{
return text;
}
string before = text.Substring(0, index);
string match = text.Substring(index, searchTerm.Length);
string after = text.Substring(index + searchTerm.Length);
return $"{before}<mark>{match}</mark>{after}";
}
}
<style>
mark {
background-color: yellow;
color: black;
}
</style>
I try to change the browser or change mark tag but i still have the same problem.
>Solution :
try changing :
<li>@GetHighlightedText(item)</li>
to :
<li> @((MarkupString)GetHighlightedText(item)) </li>