Code Snippets
/

Escape HTML Special Characters

Escape HTML Special Characters

Inserting user input into HTML without escaping is the canonical XSS vector. The five characters `&<>"'` cover most rendering contexts, but attribute values, URL attributes, and `<script>` blocks each have stricter rules. This snippet starts with the minimal map every JS dev should memorise, adds an attribute-safe variant that also escapes the backtick, and ends with a note on when to reach for a real sanitiser like DOMPurify (without bundling it).

JavaScript
Medium
3 snippets
strings
regex
utility

1,001 views

11

const HTML_ENTITIES = {
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    "'": '&#39;',
};

function escapeHtml(str) {
    if (typeof str !== 'string') return '';
    return str.replace(/[&<>"']/g, (ch) => HTML_ENTITIES[ch]);
}

console.log(escapeHtml('<script>alert("xss")</script>'));
// &lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt;
console.log(escapeHtml("Tom & Jerry's day"));
// Tom &amp; Jerry&#39;s day
console.log(escapeHtml('plain text'));
// plain text

The five characters & < > " ' are the ones that change parsing in HTML text content and double-quoted attribute values. Replacing them with named entities (&amp;, &lt;, &gt;, &quot;) and one numeric entity (&#39; for the single quote, since &apos; is not in HTML4) is enough for rendering server-generated text inside element bodies. Note that we escape & first by listing it first in the regex character class, but order inside [&<>"'] does not actually matter because each match is one character; the danger is hand-rolling sequential replace calls, where doing & last would double-encode the others. Use this function for plain text inserted between tags.