DEV Community 👩‍💻👨‍💻

Joe Enos
Joe Enos

Posted on

Show white-space properly in HTML

Often you'll need to dump some plain text to the screen with HTML. Let's address two issues with this.

First, especially user-provided data may have malicious stuff in there, like script tags - we want to ensure we don't add those to the DOM. When using ASP.NET Razor or other similar tools, the default behavior is to HTML-encode the data, which solves that problem.

The second issue is line breaks. By default, HTML treats all consecutive whitespace, including line breaks, as a single space. You can deal with this by replacing new line characters with a <br> tag. However, because of the first issue, when you encode this, the <br> text itself shows up on the page. To get around this one, you have to first encode, then do the replacement. This can get ugly.

@Html.Raw(HttpUtility.HtmlEncode(text).Replace("\r\n", "<br>").Replace("\n", "<br>").Replace("\r", "<br>"))

Instead of dealing with all that junk, there's a CSS property - white-space: pre-line - which handles line breaks for you.

<div style=white-space:pre-line>@text</div>

Now you get line breaks handled the way you want, without having to do any string replacements or special HTML encoding/decoding.

Top comments (0)

🤔 Did you know?

🌚 Dark mode is available in Settings.