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!
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
_.escapein 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
_.escapethese days.