How to Escape HTML Entities Safely (With Examples)
HTML Encoding
When to HTML-Encode
Encode user-supplied text before rendering it in HTML pages, templates, or documentation examples. This prevents browsers from interpreting input as markup and reduces XSS risk.
Real-World Examples
<script>alert(1)</script> → safe entity form for display
Tom & Jerry → ampersand escaped as &
Showing code snippets in blog posts or admin dashboards without executing tags
Common Mistakes
- Encoding already-encoded entities twice (
&lt;) - Encoding entire HTML documents instead of untrusted dynamic values only
- Relying on encoding alone in JavaScript event handlers or URLs — context matters
Edge Cases
- Attribute contexts may need quote escaping in addition to entity encoding
- Some characters have named and numeric entity forms — both are valid
- Unicode characters can use numeric entities when font support is uncertain
Security Considerations
HTML encoding is essential output escaping for text nodes, but it is not a complete XSS strategy. Combine with Content Security Policy, input validation, and framework-safe templating.
Developer Tips
- Prefer framework auto-escaping (React JSX, template engines) over manual encoding
- Encode at output time for the specific HTML context (text, attribute, JS string)
Frequently asked questions
Does HTML encoding prevent XSS?
It helps significantly when displaying untrusted text in HTML content, but you still need proper context-aware escaping and security headers.
Which characters must be encoded?
At minimum: <, >, &, and quotes in attribute values. User content displayed as text should encode all markup-significant characters.
Should I encode data before storing it in a database?
Usually no. Store raw data and encode when rendering. Encoding at storage makes searching and reuse harder.