DevToolsForYou

HTML Escape Tool in JavaScript / Node.js — Code Examples

HTML Escape Tool in JavaScript / Node.jsUse the online tool →

HTML escaping converts special characters like <, >, &, and " into their HTML entity equivalents (&lt;, &gt;, &amp;, &quot;) to prevent XSS attacks and ensure correct rendering. Here is how to escape and unescape HTML in each language.

In browsers, create a temporary DOM element to escape HTML reliably. In Node.js, use a library like he or escape manually.

Browser
// Escape using a temporary DOM element (most reliable in browsers)
function escapeHtml(str) {
  const div = document.createElement("div");
  div.appendChild(document.createTextNode(str));
  return div.innerHTML;
}

function unescapeHtml(str) {
  const div = document.createElement("div");
  div.innerHTML = str;
  return div.textContent ?? "";
}

const raw = '<script>alert("xss")</script> & "quotes"';
console.log(escapeHtml(raw));
// &lt;script&gt;alert("xss")&lt;/script&gt; &amp; "quotes"
Node.js
// npm install he
const he = require("he");

const raw = '<script>alert("xss")</script> & "quotes"';

// Escape
const escaped = he.encode(raw);
console.log(escaped);
// &#x3C;script&#x3E;alert(&#x22;xss&#x22;)&#x3C;/script&#x3E; &#x26; &#x22;quotes&#x22;

// Unescape
const unescaped = he.decode("&lt;b&gt;Hello&lt;/b&gt;");
console.log(unescaped); // <b>Hello</b>

// Minimal escaping (only the 5 critical chars)
const minimal = he.encode(raw, { useNamedReferences: true, allowUnsafeSymbols: false });
Notes & gotchas
  • The DOM-based approach works for all HTML entities automatically, but requires a browser environment.
  • For Node.js, the he library is the most complete HTML entity encoder/decoder.
  • In React, Vue, and most modern frameworks, template content is auto-escaped — only use dangerouslySetInnerHTML / v-html for trusted content.
Try it in your browser

Need to html escape/unescape without writing code? The HTML Escape Tool runs entirely in your browser — paste your input and get the result instantly. No signup, no install, no data sent to a server.

Open HTML Escape/Unescape
HTML Escape Tool in other languages