PRACTICAL GUIDE

Escape HTML Characters in the Right Context

An angle bracket can start markup in an HTML document.

Separate text from markup

An angle bracket can start markup in an HTML document. Writing its character reference lets it appear as text instead. Encoding <example> as &lt;example&gt; changes representation rather than removing the characters from the underlying message.

Handle ampersands consistently

Ampersands introduce character references, so they also need escaping when writing arbitrary plain text into an HTML text context. Re-encoding an already escaped string can produce another layer such as &amp;lt;. Know which representation you currently hold.

Decode for inspection

The decoder shows literal text so you can examine a reference or copied fragment. It does not insert the result as live markup. Copying that result into another application can have different consequences depending on how that application uses it.

Choose context-specific protection

HTML text, quoted attributes, JavaScript, CSS and URLs have different interpretation rules. This small converter demonstrates character references; it does not validate an application’s complete output-escaping strategy.

Put it into practice