<p>Does anyone know of an easy way to escape HTML from strings in <a href="http://jquery.com/" rel="noreferrer">jQuery</a>?  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.</p>

[{'answer_id': 24870, 'author': 'tghw', 'author_id': 2363, 'author_profile': 'https://Stackoverflow.com/users/2363', 'pm_score': 6, 'selected': False, 'text': '<p>If you\'re escaping for HTML, there are only three that I can think of that would be really necessary:</p>\n\n<pre><code>html.replace(/&amp;/g, "&amp;amp;").replace(/&lt;/g, "&amp;lt;").replace(/&gt;/g, "&amp;gt;");\n</code></pre>\n\n<p>Depending on your use case, you might also need to do things like <code>"</code> to <code>&amp;quot;</code>.  If the list got big enough, I\'d just use an array:</p>\n\n<pre><code>var escaped = html;\nvar findReplace = [[/&amp;/g, "&amp;amp;"], [/&lt;/g, "&amp;lt;"], [/&gt;/g, "&amp;gt;"], [/"/g, "&amp;quot;"]]\nfor(var item in findReplace)\n    escaped = escaped.replace(findReplace[item][0], findReplace[item][1]);\n</code></pre>\n\n<p><code>encodeURIComponent()</code> will only escape it for URLs, not for HTML.</p>\n'}, {'answer_id': 25207, 'author': 'travis', 'author_id': 1414, 'author_profile': 'https://Stackoverflow.com/users/1414', 'pm_score': 10, 'selected': True, 'text': '<p>Since you\'re using <a href="https://jquery.com/" rel="noreferrer">jQuery</a>, you can just set the element\'s <a href="http://api.jquery.com/text/" rel="noreferrer"><code>text</code></a> property:</p>\n\n<pre><code>// before:\n// &lt;div class="someClass"&gt;text&lt;/div&gt;\nvar someHtmlString = "&lt;script&gt;alert(\'hi!\');&lt;/script&gt;";\n\n// set a DIV\'s text:\n$("div.someClass").text(someHtmlString);\n// after: \n// &lt;div class="someClass"&gt;&amp;lt;script&amp;gt;alert(\'hi!\');&amp;lt;/script&amp;gt;&lt;/div&gt;\n\n// get the text in a string:\nvar escaped = $("&lt;div&gt;").text(someHtmlString).html();\n// value: \n// &amp;lt;script&amp;gt;alert(\'hi!\');&amp;lt;/script&amp;gt;\n</code></pre>\n'}, {'answer_id': 374176, 'author': 'Henrik N', 'author_id': 6962, 'author_profile': 'https://Stackoverflow.com/users/6962', 'pm_score': 8, 'selected': False, 'text': '<pre><code>$(\'&lt;div/&gt;\').text(\'This is fun &amp; stuff\').html(); // "This is fun &amp;amp; stuff"\n</code></pre>\n\n<p>Source: <a href="http://debuggable.com/posts/encode-html-entities-with-jquery:480f4dd6-13cc-4ce9-8071-4710cbdd56cb" rel="noreferrer">http://debuggable.com/posts/encode-html-entities-with-jquery:480f4dd6-13cc-4ce9-8071-4710cbdd56cb</a></p>\n'}, {'answer_id': 6084508, 'author': 'Wayne', 'author_id': 404535, 'author_profile': 'https://Stackoverflow.com/users/404535', 'pm_score': 3, 'selected': False, 'text': '<p>If your\'re going the regex route, there\'s an error in tghw\'s example above.</p>\n\n<pre><code>&lt;!-- WON\'T WORK -  item[0] is an index, not an item --&gt;\n\nvar escaped = html; \nvar findReplace = [[/&amp;/g, "&amp;amp;"], [/&lt;/g, "&amp;lt;"], [/&gt;/g,"&amp;gt;"], [/"/g,\n"&amp;quot;"]]\n\nfor(var item in findReplace) {\n     escaped = escaped.replace(item[0], item[1]);   \n}\n\n\n&lt;!-- WORKS - findReplace[item[]] correctly references contents --&gt;\n\nvar escaped = html;\nvar findReplace = [[/&amp;/g, "&amp;amp;"], [/&lt;/g, "&amp;lt;"], [/&gt;/g, "&amp;gt;"], [/"/g, "&amp;quot;"]]\n\nfor(var item in findReplace) {\n     escaped = escaped.replace(findReplace[item[0]], findReplace[item[1]]);\n}\n</code></pre>\n'}, {'answer_id': 10754604, 'author': 'NicolasBernier', 'author_id': 1213445, 'author_profile': 'https://Stackoverflow.com/users/1213445', 'pm_score': 4, 'selected': False, 'text': '<p><code>escape()</code> and <code>unescape()</code> are intended to encode / decode strings for URLs, not HTML.</p>\n\n<p>Actually, I use the following snippet to do the trick that doesn\'t require any framework:</p>\n\n<pre><code>var escapedHtml = html.replace(/&amp;/g, \'&amp;amp;\')\n                      .replace(/&gt;/g, \'&amp;gt;\')\n                      .replace(/&lt;/g, \'&amp;lt;\')\n                      .replace(/"/g, \'&amp;quot;\')\n                      .replace(/\'/g, \'&amp;apos;\');\n</code></pre>\n'}, {'answer_id': 10825766, 'author': 'intrepidis', 'author_id': 847235, 'author_profile': 'https://Stackoverflow.com/users/847235', 'pm_score': 5, 'selected': False, 'text': '<p>Here is a clean, clear JavaScript function. It will escape text such as "a few &lt; many" into "a few &amp;lt; many".</p>\n\n<pre><code>function escapeHtmlEntities (str) {\n  if (typeof jQuery !== \'undefined\') {\n    // Create an empty div to use as a container,\n    // then put the raw text in and get the HTML\n    // equivalent out.\n    return jQuery(\'&lt;div/&gt;\').text(str).html();\n  }\n\n  // No jQuery, so use string replace.\n  return str\n    .replace(/&amp;/g, \'&amp;amp;\')\n    .replace(/&gt;/g, \'&amp;gt;\')\n    .replace(/&lt;/g, \'&amp;lt;\')\n    .replace(/"/g, \'&amp;quot;\')\n    .replace(/\'/g, \'&amp;apos;\');\n}\n</code></pre>\n'}, {'answer_id': 11229519, 'author': 'Katharapu Ramana', 'author_id': 1486081, 'author_profile': 'https://Stackoverflow.com/users/1486081', 'pm_score': 0, 'selected': False, 'text': '<pre><code>function htmlEscape(str) {\n    var stringval="";\n    $.each(str, function (i, element) {\n        alert(element);\n        stringval += element\n            .replace(/&amp;/g, \'&amp;amp;\')\n            .replace(/"/g, \'&amp;quot;\')\n            .replace(/\'/g, \'&amp;#39;\')\n            .replace(/&lt;/g, \'&amp;lt;\')\n            .replace(/&gt;/g, \'&amp;gt;\')\n            .replace(\' \', \'-\')\n            .replace(\'?\', \'-\')\n            .replace(\':\', \'-\')\n            .replace(\'|\', \'-\')\n            .replace(\'.\', \'-\');\n    });\n    alert(stringval);\n    return String(stringval);\n}\n</code></pre>\n'}, {'answer_id': 12033826, 'author': 'Nikita Koksharov', 'author_id': 764206, 'author_profile': 'https://Stackoverflow.com/users/764206', 'pm_score': 5, 'selected': False, 'text': '<p>Try <a href="https://github.com/epeli/underscore.string" rel="noreferrer">Underscore.string</a> lib, it works with jQuery.</p>\n\n<pre><code>_.str.escapeHTML(\'&lt;div&gt;Blah blah blah&lt;/div&gt;\')\n</code></pre>\n\n<p>output:</p>\n\n<pre><code>\'&amp;lt;div&amp;gt;Blah blah blah&amp;lt;/div&amp;gt;\'\n</code></pre>\n'}, {'answer_id': 12034334, 'author': 'Tom Gruner', 'author_id': 420688, 'author_profile': 'https://Stackoverflow.com/users/420688', 'pm_score': 9, 'selected': False, 'text': '<p>There is also <a href="https://github.com/janl/mustache.js/blob/master/mustache.js#L73" rel="noreferrer">the solution from mustache.js</a></p>\n\n<pre><code>var entityMap = {\n  \'&amp;\': \'&amp;amp;\',\n  \'&lt;\': \'&amp;lt;\',\n  \'&gt;\': \'&amp;gt;\',\n  \'"\': \'&amp;quot;\',\n  "\'": \'&amp;#39;\',\n  \'/\': \'&amp;#x2F;\',\n  \'`\': \'&amp;#x60;\',\n  \'=\': \'&amp;#x3D;\'\n};\n\nfunction escapeHtml (string) {\n  return String(string).replace(/[&amp;&lt;&gt;"\'`=\\/]/g, function (s) {\n    return entityMap[s];\n  });\n}\n</code></pre>\n'}, {'answer_id': 12473399, 'author': 'Cees Timmerman', 'author_id': 819417, 'author_profile': 'https://Stackoverflow.com/users/819417', 'pm_score': -1, 'selected': False, 'text': '<p><a href="https://stackoverflow.com/a/10825766/819417">This answer</a> provides the jQuery and normal JS methods, but this is shortest without using the DOM:</p>\n\n<pre><code>unescape(escape("It\'s &gt; 20% less complicated this way."))\n</code></pre>\n\n<p>Escaped string: <code>It%27s%20%3E%2020%25%20less%20complicated%20this%20way.</code></p>\n\n<p>If the escaped spaces bother you, try:</p>\n\n<pre><code>unescape(escape("It\'s &gt; 20% less complicated this way.").replace(/%20/g, " "))\n</code></pre>\n\n<p>Escaped string: <code>It%27s %3E 20%25 less complicated this way.</code></p>\n\n<p>Unfortunately, the <code>escape()</code> function was <a href="http://www.w3schools.com/jsref/jsref_escape.asp" rel="nofollow noreferrer">deprecated in JavaScript version 1.5</a>. <code>encodeURI()</code> or <code>encodeURIComponent()</code> are alternatives, but they ignore <code>\'</code>, so the last line of code would turn into this:</p>\n\n<pre><code>decodeURI(encodeURI("It\'s &gt; 20% less complicated this way.").replace(/%20/g, " ").replace("\'", \'%27\'))\n</code></pre>\n\n<p>All major browsers still support the short code, and given the number of old websites, i doubt that will change soon.</p>\n'}, {'answer_id': 13149865, 'author': 'amrp', 'author_id': 1787210, 'author_profile': 'https://Stackoverflow.com/users/1787210', 'pm_score': 3, 'selected': False, 'text': '<p>This is a nice safe example...</p>\n\n<pre><code>function escapeHtml(str) {\n    if (typeof(str) == "string"){\n        try{\n            var newStr = "";\n            var nextCode = 0;\n            for (var i = 0;i &lt; str.length;i++){\n                nextCode = str.charCodeAt(i);\n                if (nextCode &gt; 0 &amp;&amp; nextCode &lt; 128){\n                    newStr += "&amp;#"+nextCode+";";\n                }\n                else{\n                    newStr += "?";\n                }\n             }\n             return newStr;\n        }\n        catch(err){\n        }\n    }\n    else{\n        return str;\n    }\n}\n</code></pre>\n'}, {'answer_id': 13371349, 'author': 'zrajm', 'author_id': 351162, 'author_profile': 'https://Stackoverflow.com/users/351162', 'pm_score': 5, 'selected': False, 'text': '<p>I wrote a tiny little function which does this. It only escapes <code>"</code>, <code>&amp;</code>, <code>&lt;</code> and <code>&gt;</code> (but usually that\'s all you need anyway). It is slightly more elegant then the earlier proposed solutions in that it only uses <em>one</em> <code>.replace()</code> to do all the conversion. (<strong>EDIT 2:</strong> Reduced code complexity making the function even smaller and neater, if you\'re curious about the original code see end of this answer.)</p>\n\n<pre><code>function escapeHtml(text) {\n    \'use strict\';\n    return text.replace(/[\\"&amp;&lt;&gt;]/g, function (a) {\n        return { \'"\': \'&amp;quot;\', \'&amp;\': \'&amp;amp;\', \'&lt;\': \'&amp;lt;\', \'&gt;\': \'&amp;gt;\' }[a];\n    });\n}\n</code></pre>\n\n<p>This is plain Javascript, no jQuery used.</p>\n\n<h2>Escaping <code>/</code> and <code>\'</code> too</h2>\n\n<p><strong>Edit in response to <em>mklement</em>\'s comment.</strong></p>\n\n<p>The above function can easily be expanded to include any character. To specify more characters to escape, simply insert them both in the character class in the regular expression (i.e. inside the <code>/[...]/g</code>) and as an entry in the <code>chr</code> object. (<strong>EDIT 2:</strong> Shortened this function too, in the same way.)</p>\n\n<pre><code>function escapeHtml(text) {\n    \'use strict\';\n    return text.replace(/[\\"&amp;\'\\/&lt;&gt;]/g, function (a) {\n        return {\n            \'"\': \'&amp;quot;\', \'&amp;\': \'&amp;amp;\', "\'": \'&amp;#39;\',\n            \'/\': \'&amp;#47;\',  \'&lt;\': \'&amp;lt;\',  \'&gt;\': \'&amp;gt;\'\n        }[a];\n    });\n}\n</code></pre>\n\n<p>Note the above use of <code>&amp;#39;</code> for apostrophe (the symbolic entity <code>&amp;apos;</code> might have been used instead – it is defined in XML, but was originally not included in the HTML spec and might therefore not be supported by all browsers. See: <a href="http://en.wikipedia.org/wiki/Character_encodings_in_HTML#HTML_character_references">Wikipedia article on HTML character encodings</a>). I also recall reading somewhere that using decimal entities is more widely supported than using hexadecimal, but I can\'t seem to find the source for that now though. (And there cannot be many browsers out there which does not support the hexadecimal entities.)</p>\n\n<p><strong>Note:</strong> Adding <code>/</code> and <code>\'</code> to the list of escaped characters isn\'t all that useful, since they do not have any special meaning in HTML and do not <em>need</em> to be escaped.</p>\n\n<h2>Original <code>escapeHtml</code> Function</h2>\n\n<p><strong>EDIT 2:</strong> The original function used a variable (<code>chr</code>) to store the object needed for the <code>.replace()</code> callback. This variable also needed an extra anonymous function to scope it, making the function (needlessly) a little bit bigger and more complex.</p>\n\n<pre><code>var escapeHtml = (function () {\n    \'use strict\';\n    var chr = { \'"\': \'&amp;quot;\', \'&amp;\': \'&amp;amp;\', \'&lt;\': \'&amp;lt;\', \'&gt;\': \'&amp;gt;\' };\n    return function (text) {\n        return text.replace(/[\\"&amp;&lt;&gt;]/g, function (a) { return chr[a]; });\n    };\n}());\n</code></pre>\n\n<p>I haven\'t tested which of the two versions are faster. If you do, feel free to add info and links about it here.</p>\n'}, {'answer_id': 13510502, 'author': 'Jeena', 'author_id': 63779, 'author_profile': 'https://Stackoverflow.com/users/63779', 'pm_score': 4, 'selected': False, 'text': '<p>I\'ve enhanced the mustache.js example adding the <code>escapeHTML()</code> method to the string object.</p>\n\n<pre><code>var __entityMap = {\n    "&amp;": "&amp;amp;",\n    "&lt;": "&amp;lt;",\n    "&gt;": "&amp;gt;",\n    \'"\': \'&amp;quot;\',\n    "\'": \'&amp;#39;\',\n    "/": \'&amp;#x2F;\'\n};\n\nString.prototype.escapeHTML = function() {\n    return String(this).replace(/[&amp;&lt;&gt;"\'\\/]/g, function (s) {\n        return __entityMap[s];\n    });\n}\n</code></pre>\n\n<p>That way it is quite easy to use <code>"Some &lt;text&gt;, more Text&amp;Text".escapeHTML()</code></p>\n'}, {'answer_id': 16520846, 'author': 'Gheljenor', 'author_id': 2377530, 'author_profile': 'https://Stackoverflow.com/users/2377530', 'pm_score': 2, 'selected': False, 'text': '<pre><code>(function(undefined){\n    var charsToReplace = {\n        \'&amp;\': \'&amp;amp;\',\n        \'&lt;\': \'&amp;lt;\',\n        \'&gt;\': \'&amp;gt;\'\n    };\n\n    var replaceReg = new RegExp("[" + Object.keys(charsToReplace).join("") + "]", "g");\n    var replaceFn = function(tag){ return charsToReplace[tag] || tag; };\n\n    var replaceRegF = function(replaceMap) {\n        return (new RegExp("[" + Object.keys(charsToReplace).concat(Object.keys(replaceMap)).join("") + "]", "gi"));\n    };\n    var replaceFnF = function(replaceMap) {\n        return function(tag){ return replaceMap[tag] || charsToReplace[tag] || tag; };\n    };\n\n    String.prototype.htmlEscape = function(replaceMap) {\n        if (replaceMap === undefined) return this.replace(replaceReg, replaceFn);\n        return this.replace(replaceRegF(replaceMap), replaceFnF(replaceMap));\n    };\n})();\n</code></pre>\n\n<p>No global variables, some memory optimization.\nUsage: </p>\n\n<pre><code>"some&lt;tag&gt;and&amp;symbol©".htmlEscape({\'©\': \'&amp;copy;\'})\n</code></pre>\n\n<p>result is: </p>\n\n<pre><code>"some&amp;lt;tag&amp;gt;and&amp;amp;symbol&amp;copy;"\n</code></pre>\n'}, {'answer_id': 16889423, 'author': 'd-_-b', 'author_id': 1166285, 'author_profile': 'https://Stackoverflow.com/users/1166285', 'pm_score': 0, 'selected': False, 'text': "<pre><code>function htmlDecode(t){\n   if (t) return $('&lt;div /&gt;').html(t).text();\n}\n</code></pre>\n\n<p>works like a charm</p>\n"}, {'answer_id': 17546215, 'author': 'Saram', 'author_id': 1828986, 'author_profile': 'https://Stackoverflow.com/users/1828986', 'pm_score': 5, 'selected': False, 'text': '<p>After last tests I can recommend <strong>fastest</strong> and completely <strong>cross browser</strong> compatible <strong>native javaScript</strong> (DOM) solution:</p>\n\n<pre><code>function HTMLescape(html){\n    return document.createElement(\'div\')\n        .appendChild(document.createTextNode(html))\n        .parentNode\n        .innerHTML\n}\n</code></pre>\n\n<p>If you repeat it many times you can do it with once prepared variables:</p>\n\n<pre><code>//prepare variables\nvar DOMtext = document.createTextNode("test");\nvar DOMnative = document.createElement("span");\nDOMnative.appendChild(DOMtext);\n\n//main work for each case\nfunction HTMLescape(html){\n  DOMtext.nodeValue = html;\n  return DOMnative.innerHTML\n}\n</code></pre>\n\n<p>Look at my final performance <a href="http://jsperf.com/htmlencoderegex/35" rel="noreferrer">comparison</a> (<a href="https://stackoverflow.com/a/17450136/1828986">stack question</a>).</p>\n'}, {'answer_id': 18756038, 'author': 'chovy', 'author_id': 33522, 'author_profile': 'https://Stackoverflow.com/users/33522', 'pm_score': 5, 'selected': False, 'text': '<p>Easy enough to use underscore:</p>\n\n<pre><code>_.escape(string) \n</code></pre>\n\n<p><a href="http://underscorejs.org">Underscore</a> is a utility library that provides a lot of features that native js doesn\'t provide. There\'s also <a href="https://lodash.com/">lodash</a> which is the same API as underscore but was rewritten to be more performant.</p>\n'}, {'answer_id': 25671389, 'author': 'ronnbot', 'author_id': 1712950, 'author_profile': 'https://Stackoverflow.com/users/1712950', 'pm_score': 4, 'selected': False, 'text': "<p>If you have underscore.js, use <code>_.escape</code> (more efficient than the jQuery method posted above):</p>\n\n<pre><code>_.escape('Curly, Larry &amp; Moe'); // returns: Curly, Larry &amp;amp; Moe\n</code></pre>\n"}, {'answer_id': 28219824, 'author': 'raam86', 'author_id': 1143013, 'author_profile': 'https://Stackoverflow.com/users/1143013', 'pm_score': 2, 'selected': False, 'text': '<p>You can easily do it with vanilla js.</p>\n\n<p>Simply add a text node the document. \nIt will be escaped by the browser.</p>\n\n<pre><code>var escaped = document.createTextNode("&lt;HTML TO/ESCAPE/&gt;")\ndocument.getElementById("[PARENT_NODE]").appendChild(escaped)\n</code></pre>\n'}, {'answer_id': 28905718, 'author': 'Kauê Gimenes', 'author_id': 1055711, 'author_profile': 'https://Stackoverflow.com/users/1055711', 'pm_score': -1, 'selected': False, 'text': '<p>If you are saving this information in a <strong>database</strong>, its wrong to escape HTML using a <strong>client-side</strong> script, this should be done in the <strong>server</strong>. Otherwise its easy to bypass your XSS protection.</p>\n\n<p><strong>To make my point clear, here is a exemple using one of the answers:</strong></p>\n\n<p>Lets say you are using the function escapeHtml to escape the Html from a comment in your blog and then posting it to your server.</p>\n\n<pre><code>var entityMap = {\n    "&amp;": "&amp;amp;",\n    "&lt;": "&amp;lt;",\n    "&gt;": "&amp;gt;",\n    \'"\': \'&amp;quot;\',\n    "\'": \'&amp;#39;\',\n    "/": \'&amp;#x2F;\'\n  };\n\n  function escapeHtml(string) {\n    return String(string).replace(/[&amp;&lt;&gt;"\'\\/]/g, function (s) {\n      return entityMap[s];\n    });\n  }\n</code></pre>\n\n<p>The user could:</p>\n\n<ul>\n<li>Edit the POST request parameters and replace the comment with javascript code.</li>\n<li>Overwrite the escapeHtml function using the browser console.</li>\n</ul>\n\n<p>If the user paste this snippet in the console it would bypass the XSS validation:</p>\n\n<pre><code>function escapeHtml(string){\n   return string\n}\n</code></pre>\n'}, {'answer_id': 30467671, 'author': 'C Nimmanant', 'author_id': 4761711, 'author_profile': 'https://Stackoverflow.com/users/4761711', 'pm_score': -1, 'selected': False, 'text': '<p>All solutions are useless if you dont prevent re-escape, e.g. most solutions would keep escaping <code>&amp;</code> to <code>&amp;amp;</code>.</p>\n\n<pre><code>escapeHtml = function (s) {\n    return s ? s.replace(\n        /[&amp;&lt;&gt;\'"]/g,\n        function (c, offset, str) {\n            if (c === "&amp;") {\n                var substr = str.substring(offset, offset + 6);\n                if (/&amp;(amp|lt|gt|apos|quot);/.test(substr)) {\n                    // already escaped, do not re-escape\n                    return c;\n                }\n            }\n            return "&amp;" + {\n                "&amp;": "amp",\n                "&lt;": "lt",\n                "&gt;": "gt",\n                "\'": "apos",\n                \'"\': "quot"\n            }[c] + ";";\n        }\n    ) : "";\n};\n</code></pre>\n'}, {'answer_id': 31637833, 'author': 'Dave Brown', 'author_id': 5010517, 'author_profile': 'https://Stackoverflow.com/users/5010517', 'pm_score': 2, 'selected': False, 'text': '<p><em>2 simple methods that require NO JQUERY...</em></p>\n\n<p>You can <strong>encode all characters</strong> in your string like this:</p>\n\n<pre><code>function encode(e){return e.replace(/[^]/g,function(e){return"&amp;#"+e.charCodeAt(0)+";"})}\n</code></pre>\n\n<p>Or just <strong>target the main characters</strong> to worry about <code>&amp;</code>, line breaks, <code>&lt;</code>, <code>&gt;</code>, <code>"</code> and <code>\'</code> like:</p>\n\n<p><div class="snippet" data-lang="js" data-hide="false">\r\n<div class="snippet-code">\r\n<pre class="snippet-code-js lang-js prettyprint-override"><code>function encode(r){\r\nreturn r.replace(/[\\x26\\x0A\\&lt;&gt;\'"]/g,function(r){return"&amp;#"+r.charCodeAt(0)+";"})\r\n}\r\n\r\nvar myString=\'Encode HTML entities!\\n"Safe" escape &lt;script&gt;&lt;/\'+\'script&gt; &amp; other tags!\';\r\n\r\ntest.value=encode(myString);\r\n\r\ntesting.innerHTML=encode(myString);\r\n\r\n/*************\r\n* \\x26 is &amp;ampersand (it has to be first),\r\n* \\x0A is newline,\r\n*************/</code></pre>\r\n<pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;p&gt;&lt;b&gt;What JavaScript Generated:&lt;/b&gt;&lt;/p&gt;\r\n\r\n&lt;textarea id=test rows="3" cols="55"&gt;&lt;/textarea&gt;\r\n\r\n&lt;p&gt;&lt;b&gt;What It Renders Too In HTML:&lt;/b&gt;&lt;/p&gt;\r\n\r\n&lt;div id="testing"&gt;www.WHAK.com&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n'}, {'answer_id': 35735254, 'author': 'Adam Leggett', 'author_id': 4735342, 'author_profile': 'https://Stackoverflow.com/users/4735342', 'pm_score': 5, 'selected': False, 'text': '<p>I realize how late I am to this party, but I have a very easy solution that does not require jQuery.</p>\n\n<pre><code>escaped = new Option(unescaped).innerHTML;\n</code></pre>\n\n<p>Edit: This does not escape quotes. The only case where quotes would need to be escaped is if the content is going to be pasted inline to an attribute within an HTML string. It is hard for me to imagine a case where doing this would be good design.</p>\n\n<p>Edit 3: For the fastest solution, check the answer above from Saram. This one is the shortest.</p>\n'}, {'answer_id': 46685127, 'author': 'iamandrewluca', 'author_id': 4671932, 'author_profile': 'https://Stackoverflow.com/users/4671932', 'pm_score': 2, 'selected': False, 'text': '<p>Plain JavaScript escaping example:</p>\n\n<pre><code>function escapeHtml(text) {\n    var div = document.createElement(\'div\');\n    div.innerText = text;\n    return div.innerHTML;\n}\n\nescapeHtml("&lt;script&gt;alert(\'hi!\');&lt;/script&gt;")\n// "&amp;lt;script&amp;gt;alert(\'hi!\');&amp;lt;/script&amp;gt;"\n</code></pre>\n'}, {'answer_id': 57956081, 'author': 'chickens', 'author_id': 1602301, 'author_profile': 'https://Stackoverflow.com/users/1602301', 'pm_score': 2, 'selected': False, 'text': '<p><strong>ES6 one liner</strong> for the <a href="https://github.com/janl/mustache.js/blob/master/mustache.js#L73" rel="nofollow noreferrer">solution from mustache.js</a></p>\n\n<pre><code>const escapeHTML = str =&gt; (str+\'\').replace(/[&amp;&lt;&gt;"\'`=\\/]/g, s =&gt; ({\'&amp;\': \'&amp;amp;\',\'&lt;\': \'&amp;lt;\',\'&gt;\': \'&amp;gt;\',\'"\': \'&amp;quot;\',"\'": \'&amp;#39;\',\'/\': \'&amp;#x2F;\',\'`\': \'&amp;#x60;\',\'=\': \'&amp;#x3D;\'})[s]);\n</code></pre>\n'}, {'answer_id': 65462577, 'author': "Christian d'Heureuse", 'author_id': 337221, 'author_profile': 'https://Stackoverflow.com/users/337221', 'pm_score': 0, 'selected': False, 'text': '<p>A speed-optimized version:</p>\n<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">\r\n<div class="snippet-code">\r\n<pre class="snippet-code-js lang-js prettyprint-override"><code>function escapeHtml(s) {\n   let out = "";\n   let p2 = 0;\n   for (let p = 0; p &lt; s.length; p++) {\n      let r;\n      switch (s.charCodeAt(p)) {\n         case 34: r = "&amp;quot;"; break;  // "\n         case 38: r = "&amp;amp;" ; break;  // &amp;\n         case 39: r = "&amp;#39;" ; break;  // \'\n         case 60: r = \'&amp;lt;\'  ; break;  // &lt;\n         case 62: r = \'&amp;gt;\'  ; break;  // &gt;\n         default: continue;\n      }\n      if (p2 &lt; p) {\n         out += s.substring(p2, p);\n      }\n      out += r;\n      p2 = p + 1;\n   }\n   if (p2 == 0) {\n      return s;\n   }\n   if (p2 &lt; s.length) {\n      out += s.substring(p2);\n   }\n   return out;\n}\n\nconst s = "Hello &lt;World&gt;!";\ndocument.write(escapeHtml(s));\nconsole.log(escapeHtml(s));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n'}, {'answer_id': 70677639, 'author': 'oscar castellon', 'author_id': 1283517, 'author_profile': 'https://Stackoverflow.com/users/1283517', 'pm_score': 0, 'selected': False, 'text': "<p>For escape html specials (UTF-8)</p>\n<pre><code>function htmlEscape(str) {\n  return str\n      .replace(/&amp;/g, '&amp;amp;')\n      .replace(/&quot;/g, '&amp;quot;')\n      .replace(/'/g, '&amp;#39;')\n      .replace(/&lt;/g, '&amp;lt;')\n      .replace(/&gt;/g, '&amp;gt;')\n      .replace(/\\//g, '&amp;#x2F;')\n      .replace(/=/g,  '&amp;#x3D;')\n      .replace(/`/g, '&amp;#x60;');\n}\n</code></pre>\n<p>For unescape html specials (UTF-8)</p>\n<pre><code>function htmlUnescape(str) {\n  return str\n      .replace(/&amp;amp;/g, '&amp;')\n      .replace(/&amp;quot;/g, '&quot;')\n      .replace(/&amp;#39;/g, &quot;'&quot;)\n      .replace(/&amp;lt;/g, '&lt;')\n      .replace(/&amp;gt;/g, '&gt;')\n      .replace(/&amp;#x2F/g, '/')\n      .replace(/&amp;#x3D;/g, '=')\n      .replace(/&amp;#x60;/g, '`');\n}\n</code></pre>\n"}]
['https://Stackoverflow.com/questions/24816', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2657/']