So I know how to replace newlines in my C# code. But replacing a newline for a <br />
tag isn't always very correct.
So I was wondering what kind of strategy do others use? The correct way I guess would be to use <p>
tags and <br />
tags.
Here are some examples of the results I would like to get.
If there is no newline I want the text to wrapped in a <p>
tags.
This text contains no newlines
<p>This text contains no newlines</p>
If the text contains a newline I want it to be replaced by a <br />
tag and be wrapped in <p>
tags.
This text contains
1 newline
<p>This text contains<br /> 1 newline.</p>
If there are 'double newlines' I want that block to be wrapped in <p>
tags.
This is a text with 'double newlines' at the end.
This is a text with no newline at the end.
<p>This a text with 'double newlines at the end.</p>
<p>This is a text with no newline at the end.</p>
I could write more examples/combination but I guess it's somewhat clear what I mean.
Thanks in advance.
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).
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With