Skip to content Skip to sidebar Skip to footer

Replace Newlines With

Paragraph And With
Tags

So I know how to replace newlines in my C# code. But replacing a newline for a
tag isn't always very correct. So I was wondering what kind of strategy do others use?

Solution 1:

Here's a way you could do it using only simple string replacements:

    string result = "<p>" + text
        .Replace(Environment.NewLine + Environment.NewLine, "</p><p>")
        .Replace(Environment.NewLine, "<br />")
        .Replace("</p><p>", "</p>" + Environment.NewLine + "<p>") + "</p>";

Note that your text must be HTML-escaped first otherwise you could be at risk of cross-site scripting attacks. (Note: even using <pre> tags still has a cross-site scripting risk).


Solution 2:

You could just leave it alone and use CSS to render the breaks correctly. Here is a complicated example that is a kind of "pretty" replacement for the <pre> but you are using a <p> instead:

<p style="padding: 1em; line-height: 1.1em; font-family: monospace; white-space: pre; overflow: auto; background-color: rgb(240,255,240); border: thin solid rgb(255,220,255);">

Text goes here.

</p>


Post a Comment for "Replace Newlines With

Paragraph And With
Tags"