Encoding and security guides

HTML escaping: entity encoding depends on output context

Escape plain text safely while distinguishing HTML attributes, URLs, scripts and rich HTML sanitization.

Nav Tools ·

Prefer text insertion for plain text

When displaying a user's plain text in a DOM node, textContent avoids interpreting it as HTML. Entity encoding is useful for serialized HTML text.

The site's entity tool escapes the five basic entities. Its result is a representation, not a universal sanitizer.

Input: <b>A&B</b>
HTML text: &lt;b&gt;A&amp;B&lt;/b&gt;

Match the output context

A quoted HTML attribute needs its own escaping rules. JavaScript, CSS and URL positions have different grammars and validation requirements.

JSON string escaping is not HTML escaping. Do not paste one encoded value into every context and assume the browser treats it as text.

Validate URL schemes before insertion

Encoding an address does not make a dangerous scheme acceptable. Apply an allowlist such as HTTPS when building an external link.

After URL validation, use a safe attribute-setting API or correct attribute encoding. Encoding and protocol validation solve separate parts of the problem.

Sanitize intentional rich HTML

If markup is intentionally allowed, escaping every tag destroys that feature, while raw insertion accepts unwanted elements or attributes.

Use a maintained sanitizer with an explicit policy. Test decoding and double encoding at boundaries; never repeatedly decode until untrusted text becomes executable markup.

References

← Encoding and security guides