Returns text transformed into HTML using simple formatting rules. Two or more consecutive newlines(\n\n or \r\n\r\n) are considered a paragraph and wrapped in tags. One newline (\n or \r\n) is considered a linebreak and a
tag is appended. This method does not remove the newlines from the text.
You can pass any HTML attributes into html_options. These will be added to all created paragraphs.
Options
:sanitize - If false, does not sanitize text.
:wrapper_tag - String representing the wrapper tag, defaults to "p"
static string ToHtml(string text, bool sanitize = true, string? wrap = null)
{
var normalized = text.Replace("\r\n", "\n");
if (sanitize)
normalized = WebUtility.HtmlEncode(normalized);
var paragraphs = text.Split("\n\n")
.Select(paragraph =>
{
var lines = paragraph.Split("\n");
return string.Join("\n<br/>", lines);
});
var htmlText = string.Join("\n\n", paragraphs.Select(p => $"<p>\n{p}\n</p>"));
return wrap != null
? $"<{wrap}>\n{htmlText}\n</{wrap}>"
: htmlText;
}