Simple text to HTML conversion

Viewed 41544

I have a very simple asp:textbox with the multiline attribute enabled. I then accept just text, with no markup, from the textbox. Is there a common method by which line breaks and returns can be converted to <p> and <br/> tags?

I'm not looking for anything earth shattering, but at the same time I don't just want to do something like:

html.Insert(0, "<p>");
html.Replace(Enviroment.NewLine + Enviroment.NewLine, "</p><p>");
html.Replace(Enviroment.NewLine, "<br/>");
html.Append("</p>");

The above code doesn't work right, as in generating correct html, if there are more than 2 line breaks in a row. Having html like <br/></p><p> is not good; the <br/> can be removed.

6 Answers

Combining all previous plus considering titles and subtitles within the text comes up with this:

public static string ToHtml(this string text)
{
    var sb = new StringBuilder();

    var sr = new StringReader(text);
    var str = sr.ReadLine();
    while (str != null)
    {
        str = str.TrimEnd();
        str.Replace("  ", " &nbsp;");
        if (str.Length > 80)
        {
            sb.AppendLine($"<p>{str}</p>");
        }
        else if (str.Length > 0)
        {
            sb.AppendLine($"{str}</br>");
        }
        str = sr.ReadLine();
    }

    return sb.ToString();
}

the snippet could be enhanced by defining rules for short strings

Related