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.
No need for a jQuery function - it's built into JavaScript itself - encodeURIComponent()
@brad - escapeURIComponent() will work better than escape() for UTF-8 special characters like ö...
If you're escaping for HTML, there are only three that I can think of that would be really necessary:
html.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
Depending on your use case, you might also need to do things like " to "
. If the list got big enough, I'd just use an array:
var escaped = html;
var findReplace = [[/&/g, "&"], [/</g, "<"], [/>/g, ">"], [/"/g, """]]
for(item in findReplace)
escaped = escaped.replace(item[0], item[1]);
escapeURIComponent()
will only escape it for URLs, not for HTML.
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"><script>alert('hi!');</script></div>
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!
Instead of using jQuery I use the below function to strip out HTML.
function stripHTML(string) {
return string.replace(/<(.|\n)*?>/g, '');
}
$('<div/>').text('This is fun & stuff').html(); // "This is fun & 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?