Escaping HTML strings with jQuery
There is also the solution from mustache.js
var entityMap = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''', '/': '/', '`': '`', '=': '='};function escapeHtml (string) { return String(string).replace(/[&<>"'`=\/]/g, function (s) { return entityMap[s]; });}
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>";// set a DIV's text:$("div.someClass").text(someHtmlString);// after: // <div class="someClass"><script>alert('hi!');</script></div>// get the text in a string:var escaped = $("<div>").text(someHtmlString).html();// value: // <script>alert('hi!');</script>
$('<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