Complete Guide 4 min read

HTML Entity Encoding: When and How to Encode Special Characters

Understand HTML entities, when to encode characters, and how to avoid XSS vulnerabilities through proper encoding.

html entitieshtml encodinghtml special charactershtml entity encoderxss prevention

What Are HTML Entities?

HTML entities are codes that represent special characters in HTML. They exist because some characters have special meaning in HTML (< and > define tags, & starts entities) and others are not in the ASCII character set.

Common HTML Entities

CharacterEntityUse Case

|---|---|---|

<<Less than sign in text
>>Greater than sign in text
&&Ampersand in text
""Double quote in attributes
''Single quote in attributes
©©Copyright symbol
®®Registered trademark
Trademark symbol
Indian Rupee sign
Em dash
Ellipsis

Why HTML Encoding Matters for Security

Cross-site scripting (XSS) is one of the most common web vulnerabilities. It occurs when user-supplied input is displayed in HTML without encoding.

Vulnerable:

Hello,

If username =

This executes the script in every visitor's browser.

Safe:

Hello,

Encodes < to <, so the script tag is displayed as text, not executed.

When to Encode vs Not Encode

Encode when: Displaying user-supplied content in HTML. Inserting database content into HTML. Reflecting URL parameters in pages.

Do not encode when: Setting HTML content programmatically using DOM APIs (textContent handles encoding automatically). Using frameworks that auto-escape (React, Angular, Vue all escape by default).

Frequently asked questions

Why do I need to encode HTML entities?

To display special characters correctly and to prevent XSS attacks. Characters like <, >, and & have special meaning in HTML and must be encoded as &lt;, &gt;, and &amp; when appearing as text content.

Does React handle HTML encoding automatically?

Yes — React automatically encodes all variables rendered with JSX using curly braces: {variable}. This is why XSS is much harder in React applications than in server-side templating.

Try this tool on Lazyblink

Put this guide into practice with our free online tool — no signup required.

Open tool