Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render a string in HTML and preserve spaces and linebreaks

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)

like image 788
Dan dot net Avatar asked Feb 29 '12 01:02

Dan dot net


People also ask

How do you preserve space in HTML?

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.

How do you keep a space in a string?

Replace the spaces with &nbsp; (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.

How do you preserve all spaces and linebreaks in HTML?

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.

How do I preserve line breaks when getting text from a textarea?

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.


1 Answers

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>
like image 93
pete Avatar answered Oct 09 '22 12:10

pete