I have an MVC3 app that has a details page. As part of that I have a description (retrieved from a db) that has spaces and new lines. When it is rendered the new lines and spaces are ignored by the html. I would like to encode those spaces and new lines so that they aren't ignored.
How do you do that?
I tried HTML.Encode but it ended up displaying the encoding (and not even on the spaces and new lines but on some other special characters)
The HTML <pre> tag defines preformatted text preserving both whitespace and line breaks in the HTML document. This tag is also commonly referred to as the <pre> element.
Replace the spaces with (the HTML escape sequence for a space). Whitespace is ignored by HTML interpreters, so any markup with more than 1 space next to each other will be treated as a single space.
The <pre> tag defines preformatted text. Text in a <pre> element is displayed in a fixed-width font, and the text preserves both spaces and line breaks. The text will be displayed exactly as written in the HTML source code.
To preserve line breaks when getting text from a textarea with JavaScript, we can replace whitespace characters with '<br>\n' . const post = document. createElement("p"); post. textContent = postText; post.
Just style the content with white-space: pre-wrap;
.
div { white-space: pre-wrap; }
<div> This is some text with some extra spacing and a few newlines along with some trailing spaces and five leading spaces thrown in for good measure </div>
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