Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rendering newlines in escaped html

We have a display message that is auto-generated by default, but may be overridden by GET vars from the url. Since we need to treat the message as user input, it must be escaped for display. However, we want to retain the ability to include newlines.

Newlines as <br>
This won't work because escaping HTML destroys the <br> tag.

Newlines as \n
I can't figure out how to get \n to render as newlines. I thought putting it in a tag would render correctly, but no luck: http://jsfiddle.net/7L932/

like image 256
Yarin Avatar asked Oct 02 '12 16:10

Yarin


People also ask

How do you show newlines in HTML?

Instead of using block elements for putting elements in new lines, you can use the line break tag: br . In cases like sentences, using the br tag serves as a visual line break and doesn't affect accessibility.

How do you escape a line break in HTML?

Breaking strings using Escape sequence: The escape sequence used to create a new line in Windows and Linux is \n , but for a few older macs \r is used.

What does HTML escaped mean?

Escaping in HTML means, that you are replacing some special characters with others. In HTML it means usally, you replace e. e.g < or > or " or & . These characters have special meanings in HTML. Imagine, you write <b>hello, world</b> And the text will appear as hello, world.

Does HTML ignore newline?

HTML ignores newlines by default in most HTML elements. One element that is an exception to this rule is the textarea element (the textarea element isn't available directly with ASP.NET controls, but it's what's rendered with ASP.NET when you set a TextBox control's TextMode property to multiline .


2 Answers

Escape the HTML, and then replace \n with <br>.

In case you want to use \n, I fix your fiddle for you http://jsfiddle.net/hr3bg/

like image 74
Prinzhorn Avatar answered Sep 20 '22 14:09

Prinzhorn


What you're doing is more or less fine, except for you should put \n character (newline), not the escape sequence in your html (and what Prinzhorn says also makes perfect sense, so I'll go upvote him).

like image 34
Michael Krelin - hacker Avatar answered Sep 22 '22 14:09

Michael Krelin - hacker