使用 jQuery 转义 HTML
我想出了一个使用 jQuery 转义 HTML 的方法,我想知道是否有人发现它有问题。
$('<i></i>').text(TEXT_TO_ESCAPE).html();
标签只是一个虚拟标签,因为 jQuery 需要一个容器来设置文本。
也许有更简单的方法来做到这一点吗?请注意,我需要将文本存储在变量中,而不是用于显示(否则我可以调用 elem.text(TEXT_TO_ESCAPE);)。
谢谢!
I came up with a hack to escape HTML using jQuery and I'm wondering if anyone sees a problem with it.
$('<i></i>').text(TEXT_TO_ESCAPE).html();
The <i>
tag is just a dummy as jQuery needs a container to set the text of.
Is there perhaps an easier way to do this? Note that I need the text stored in a variable, not for display (otherwise I could just call elem.text(TEXT_TO_ESCAPE);
).
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是一种非常标准的方法,但我的版本使用了
:
正如 Mike Samuel 指出的那样,这在技术上并不是 100% 安全,但在实践中可能相当安全。
当前的 Prototype.js 是这样做的:
但它曾经使用“将文本放入 div 并提取 HTML”技巧。
Underscore 中还有
_.escape
,它的作用是这样的:差不多了与 Prototype 的方法相同。我最近编写的大多数 JavaScript 都可以使用 Underscore,所以这些天我倾向于使用
_.escape
。That's a pretty standard way of doing it, my version used a
<div>
though:This isn't technically 100% safe though as Mike Samuel notes but it is probably pretty safe in practice.
The current Prototype.js does this:
But it used to use the "put text in a div and extract the HTML" trick.
There's also
_.escape
in Underscore, that does it like this:That's pretty much the same approach as Prototype's. Most of the JavaScript I do lately has Underscore available so I tend to use
_.escape
these days.无法保证
html()
会完全转义,因此连接后结果可能不安全。html()
基于innerHTML
,浏览器可以在不违反很多期望的情况下实现innerHTML
,以便$(" ").text("1 <").html()
是"1 <"
,而$(" ").text("b>").html()
是"b>"
。然后,如果您连接这两个单独的安全结果,您将得到
"1 "
,这显然不是两个纯文本片段连接的 HTML 版本。因此,从首要原则来看,这种方法并不安全,并且没有广泛遵循的
innerHTML
规范(尽管 HTML5 确实解决了这个问题)。检查它是否达到您想要的效果的最佳方法是测试像这样的极端情况。
There is no guarantee that
html()
will be completely escaped so the result might not be safe after concatenation.html()
is based oninnerHTML
, and a browser could, without violating lots of expectations, implementinnerHTML
so that$("<i></i>").text("1 <").html()
is"1 <"
, and that$("<i></i>").text("b>").html()
is"b>"
.Then if you concatenate those two individually safe results, you get
"1 <b>"
which will obviously not be the HTML version of the concatenation of the two plaintext pieces.So, this method is not safe by deduction from first principles, and there's no widely followed spec of
innerHTML
(though HTML5 does address it).The best way to check if it does what you want is to test corner cases like this.
那应该有效。这基本上就是 Prototype.js 库的工作方式,或者至少是过去的工作方式。我通常通过三次调用“.replace()”来完成此操作,但这主要只是一种习惯。
That should work. That's basically how the Prototype.js library does it, or at least how it used to do it. I generally do it with three calls to ".replace()" but that's mostly just a habit.