Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
78
rated 0 times [  80] [ 2]  / answers: 1 / hits: 70669  / 13 Years ago, mon, may 16, 2011, 12:00:00

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!


More From » jquery

 Answers
106

That's a pretty standard way of doing it, my version used a <div> though:



return $('<div/>').text(t).html();


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:



function escapeHTML() {
return this.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
}


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:



// List of HTML entities for escaping.
var htmlEscapes = {
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'': '&quot;',
': '&#x27;',
'/': '&#x2F;'
};

// Regex containing the keys listed immediately above.
var htmlEscaper = /[&<>'/]/g;

// Escape a string for HTML interpolation.
_.escape = function(string) {
return ('' + string).replace(htmlEscaper, function(match) {
return htmlEscapes[match];
});
};


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.


[#92214] Saturday, May 14, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kayden

Total Points: 546
Total Questions: 102
Total Answers: 95

Location: Virgin Islands (U.S.)
Member since Fri, Mar 4, 2022
2 Years ago
;