Escaping HTML strings with jQuery Escaping HTML strings with jQuery javascript javascript

Escaping HTML strings with jQuery


There is also the solution from mustache.js

var entityMap = {  '&': '&',  '<': '<',  '>': '>',  '"': '"',  "'": '&#39;',  '/': '&#x2F;',  '`': '&#x60;',  '=': '&#x3D;'};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>