JavaScript Snippet

Escape HTML Special Characters

Difficulty: Medium

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).

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

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.