How can I get newlines into $.text(), or, how do I make $.append() safe from HTML?
I have a chat window (using a <div>
) that sometimes needs to get multiline entries. Until now, I've simply replaced incoming \n
with <br>
and displayed the text with .append()
. Unfortunately, I've discovered leaving a naked .append()
based on user input allows the user to insert arbitrary HTML, which will then be executed by the browser. Discovered this while copying a random StackOverflow page to it (to test large sends) and in it was a <link>
tag, which promptly caused the browser to try to download the CSS file.
Changing this method to use .text()
solved that particular problem, but now I am unable to display newlines. <br>
s开发者_高级运维 come through as literal text rather than HTML, and \n
doesn't seem to have any effect.
Any suggestions? Should I use .append()
but find some way to escape all HTML tags except <br>
? Or is there a way to slip newlines in to .text()
? Or is there a third option I'm missing completely?
You can use html()
and <br>
as long as you escape other characters that may be special in HTML. eg.
function encodeHTML(s) {
return s.replace(/&/g, '&').replace(/</g, '<').replace(/"/g, '"');
}
$('#something').append(encodeHTML(userinput).replace(/\n/g, '<br>'));
You might also consider turning \n\n
into a paragraph break.
The other approach would be to continue using text()
but set a white-space: pre-wrap
style to keep the \n
characters as line breaks
Since IE prior to version 8 doesn't support this you would need a fallback style to set white-space: pre; word-wrap: break-word;
for that browser. Other older and obscure browsers may also not support this.
Use a <pre>
element to preserve newlines in plain text (among other things).
http://www.codetoad.com/html/text/pre_tag.asp
If you want to insert html tags, you should be using $.html()
, not $.text()
.
If you want them to be able to chat HTML (As text):
You can escape the HTML elements first, by replacing < with < and > with > and then replace the new lines with BR tags.
精彩评论