· Igor Ilic

HTML entities and escaping: XSS prevention for developers

Why HTML escaping matters

When user input is rendered as HTML, special characters like < and > can be interpreted as markup. This is how cross-site scripting (XSS) attacks work — an attacker injects malicious scripts that run in your users' browsers.

HTML escaping converts these dangerous characters into safe entity references that browsers display as text instead of interpreting as code.

The five essential HTML entities

CharacterEntityDescription
<&lt;Less than (opens HTML tags)
>&gt;Greater than (closes HTML tags)
&&amp;Ampersand (starts entities)
"&quot;Double quote (breaks attribute values)
'&#39;Single quote (breaks attribute values)

When to escape

  • Any time you render user-generated content in HTML
  • When displaying form input values in the UI
  • In URL parameters that contain user data
  • When rendering markdown or rich text that could contain HTML

Context matters

HTML escaping is context-dependent. A value that is safe inside a paragraph tag might break a script tag or a URL attribute. Always use the escaping function appropriate to the output context.

Try the HTML encoder

The HTML encoder and HTML decoder let you quickly escape or unescape text. Use them to test edge cases and verify your escaping logic.