如何在javascript中转义一些html? [英] How do I escape some html in javascript?
本文介绍了如何在javascript中转义一些html?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
鉴于文字
<b>This is some text</b>
我想将它写入我的页面,以便它显示如下:
I want to write it to my page so that it shows up like this:
< b>这是一些文字< / b>
而且不喜欢这个
这是一些文字
使用 escape(< b>这是一些文字< / b>)
在firefox中给了我这个可爱的宝石
using escape("<b>This is some text</b>")
gives me this lovely gem in firefox
%3Cb%3EThis%20is%20some%20text%3C/b%3E
<不是我所追求的事情。有什么想法吗?
not exaclty what I'm after. Any ideas?
推荐答案
这应该适合你: http://blog.nickburwell.com/2011/02/escape-html-tags-in-javascript.html
function escapeHTML( string )
{
var pre = document.createElement('pre');
var text = document.createTextNode( string );
pre.appendChild(text);
return pre.innerHTML;
}
安全警告
该函数不会转义单引号和双引号,如果在错误的上下文中使用,可能仍会导致XSS。例如:
The function doesn't escape single and double quotes, which if used in the wrong context, may still lead to XSS. For example:
var userWebsite = '" onmouseover="alert(\'gotcha\')" "';
var profileLink = '<a href="' + escapeHtml(userWebsite) + '">Bob</a>';
var div = document.getElemenetById('target');
div.innerHtml = profileLink;
// <a href="" onmouseover="alert('gotcha')" "">Bob</a>
Thanks to buffer for pointing out this case. Snippet taken out of this blog post.
这篇关于如何在javascript中转义一些html?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文