views:

25999

answers:

8

Does anyone know of an easy way to escape HTML from strings in jQuery? I need to be able to pass an arbitrary string and have it properly escaped for display in an HTML page (preventing JavaScript/HTML injection attacks). I'm sure it's possible to extend jQuery to do this, but I don't know enough about the framework at the moment to accomplish this.

A: 

No need for a jQuery function - it's built into JavaScript itself - encodeURIComponent()

ceejayoz
That's URL escaping, not HTML escaping.
Grumdrig
A: 

@brad - escapeURIComponent() will work better than escape() for UTF-8 special characters like ö...

ceejayoz
escapeURIComponent() does not exist, it is encodeURIComponent()
Seldaek
+14  A: 

If you're escaping for HTML, there are only three that I can think of that would be really necessary:

html.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");

Depending on your use case, you might also need to do things like " to &quot;. If the list got big enough, I'd just use an array:

var escaped = html;
var findReplace = [[/&/g, "&amp;"], [/</g, "&lt;"], [/>/g, "&gt;"], [/"/g, "&quot;"]]
for(item in findReplace)
    escaped = escaped.replace(item[0], item[1]);

escapeURIComponent() will only escape it for URLs, not for HTML.

tghw
Jed Schmidt
You are correct. I will correct it.
tghw
+37  A: 

Since you're using jQuery, you can just set the element's text property:

// before:
// <div class="someClass">text</div>
var someHtmlString = "<script>alert('hi!');</script>";
$("div.someClass").text(someHtmlString);
// after: 
// <div class="someClass">&lt;script&gt;alert('hi!');&lt;/script&gt;</div>
travis
You missed the point that you have to access $("div.someClass").html() to get the escaped version out.
Morten Christiansen
A: 

Thanks for the answers! I agree, escapeURIComponent() isn't exactly what I was looking for since it is meant for escaping URLs and not HTML. I didn't realize that .text() in jQuery would escape my HTML strings. That is really what I was looking for. Thanks @travis!

Page Brooks
escapeURIComponent() does not exist, it is encodeURIComponent()
Seldaek
A: 

Instead of using jQuery I use the below function to strip out HTML.

function stripHTML(string) { 
    return string.replace(/<(.|\n)*?>/g, ''); 
}
Jahangir
+22  A: 
$('<div/>').text('This is fun & stuff').html(); // "This is fun &amp; stuff"

Source: http://debuggable.com/posts/encode-html-entities-with-jquery:480f4dd6-13cc-4ce9-8071-4710cbdd56cb

Could the original poster edit the question title to clarify this question is about HTML entity escaping, not URL encoding?

Henrik N
A: 

sorry posted incorrectly, trying to delete...

leslchan