Posted on

If you have text on the server that may have line breaks, you may have gone through a series of steps to get it to display properly.

First, if you weren’t really thinking about it, you just dump the output to the screen. ASP.NET and others HTML encode it, so you generally don’t have to worry about any kind of script injection. But the line breaks aren’t handled properly.

<div id=output>@message</div>

Next thing to try, replacing line breaks with a BR tag. Of course, since it’s encoded, the HTML shows up as text, and that’s no good.

<div id=output>@(
message.Replace("\r\n", "<br>").Replace("\n", "<br>").Replace("\r", "<br>")

Ok, now you need to use Html.Raw, but you can’t do it on the whole string because that will put the dangerous raw text into the page. So you have to encode the message, after replacing the line breaks, then get the raw HTML. That gets you the result you want, but it’s really ugly.

<div id=output>@Html.Raw(
.Replace("\r\n", "<br>").Replace("\n", "<br>").Replace("\r", "<br>")

Thankfully there’s a CSS property for this – white-space pre-line will show line breaks properly with no extra work.

<div id=output style=white-space:pre-line;>@message</div>

View code on GitHub

Leave a Reply

Your email address will not be published. Required fields are marked *