using Markdig;
using System.Text.RegularExpressions;
namespace WebApp.Services;
///
/// Helper class for rendering markdown to HTML.
///
public static class MarkdownHelper
{
private static readonly MarkdownPipeline _pipeline = new MarkdownPipelineBuilder()
.UseAdvancedExtensions()
.Build();
///
/// Converts markdown text to HTML.
///
/// The markdown text to convert.
/// HTML string ready for rendering.
public static string ToHtml(string? markdown)
{
if (string.IsNullOrWhiteSpace(markdown))
return string.Empty;
var html = Markdown.ToHtml(markdown, _pipeline);
// Add target="_blank" and rel="noopener noreferrer" to all links
html = Regex.Replace(html, @"]*?)href=""([^""]*?)""([^>]*?)>",
match =>
{
var beforeHref = match.Groups[1].Value;
var href = match.Groups[2].Value;
var afterHref = match.Groups[3].Value;
// Check if target is already present
if (Regex.IsMatch(beforeHref + afterHref, @"target\s*=", RegexOptions.IgnoreCase))
{
return match.Value; // Return unchanged if target already exists
}
// Add target="_blank" and rel="noopener noreferrer"
return $"";
},
RegexOptions.IgnoreCase);
return html;
}
}