Created
August 19, 2023 06:50
-
-
Save 01Vladimir10/2bb95ad337476b66263daa7e9d794d35 to your computer and use it in GitHub Desktop.
Blazor safely highlight text in a string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using AdminPwaEditor.Web.Client.Components.Base; | |
using Microsoft.AspNetCore.Components; | |
using Microsoft.AspNetCore.Components.Rendering; | |
namespace AdminPwaEditor.Web.Client.Components.Controls; | |
public class HighlightedText : BaseComponent | |
{ | |
[Parameter, EditorRequired] public string Text { get; set; } = ""; | |
[Parameter] public string? Highlight { get; set; } = ""; | |
[Parameter] public string HighlightClass { get; set; } = "bg-primary-color-variant fw-semibold"; | |
protected override void BuildRenderTree(RenderTreeBuilder builder) | |
{ | |
if (string.IsNullOrWhiteSpace(Highlight) || !Text.Contains(Highlight, StringComparison.OrdinalIgnoreCase)) | |
{ | |
builder.AddContent(0, Text); | |
return; | |
} | |
var text = Text; | |
builder.OpenElement(0, "p"); | |
for (var i = 1;;) | |
{ | |
var index = text.IndexOf(Highlight, StringComparison.OrdinalIgnoreCase); | |
if (index < 0) | |
{ | |
builder.AddContent(i, text); | |
break; | |
} | |
builder.AddContent(i++, text[..index]); | |
builder.OpenElement(i++, "span"); | |
builder.AddAttribute(i++, "class", HighlightClass); | |
builder.AddContent(i++, text.Substring(index, Highlight.Length)); | |
builder.CloseElement(); | |
text = text[(index + Highlight.Length)..]; | |
} | |
builder.CloseElement(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment