Rendering newlines in escaped html

我们两清 提交于 2019-12-07 09:00:46

问题


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/


回答1:


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).




回答2:


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/




回答3:


Your theory's sound, but \n is a not an HTML-recognised way of inserting a new line. It either comes in explicitly (as I've inserted in a new .linebreaks element) as a literal return in the markup, or, if you're using some intermediary scripting language that does recognise \n (like JS), do that (as I've done to your first .linebreaks with the jQuery code I inserted.

See my tweak to your example: http://jsfiddle.net/barney/7L932/2/



来源:https://stackoverflow.com/questions/12694110/rendering-newlines-in-escaped-html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!