DEV Community

Sanjaya Sahu
Sanjaya Sahu

Posted on

HTML Entities: 5 Escaping Mistakes That Cause Bugs and XSS

Escaping looks trivial, but mistakes here cause broken pages and security holes.

1. Escaping only <

At minimum escape & < > " '. Missing quotes breaks attribute values.

2. Escaping in the wrong context

HTML text, attributes, URLs and JavaScript each need different escaping. HTML entities do not protect you inside a <script> block.

3. Double escaping

Seeing &amp;lt; on a page means data was escaped twice. Escape once, on output.

4. Using innerHTML for text

Prefer textContent, which never parses markup.

el.textContent = userInput; // safe
el.innerHTML = userInput;   // risky
Enter fullscreen mode Exit fullscreen mode

5. Forgetting the non-breaking space

&nbsp; is not a normal space, so it breaks string comparison and word wrapping.

Convert quickly

The HTML entities encoder/decoder is handy for checking what a string really contains. It is free and in-browser at webdevtoolbox.com.

Top comments (0)