Angle brackets turning into escaped HTML entities

HTML escaping is context-specific output encoding

The same character may require different handling depending on whether it is placed in HTML text, an attribute, a URL, or a script string. Escaping is not one fixed transformation. It is a set of context-specific encodings, and the right one depends on where the data is going, not on what the data looks like.

This is the idea behind the phrase “output encoding”: you encode data at the moment it leaves your code and enters a new language — HTML, a URL, JavaScript, CSS, or SQL. The same user-supplied name can be perfectly safe in one of those languages and dangerous in another. If you encode for the wrong context, the browser may undo your encoding, or the dangerous characters may survive in exactly the form the new language treats as code.

What escaping actually does

Escaping replaces characters that have special meaning in a target language with a harmless representation that the language will display as text rather than execute. In HTML text, for example, a less-than sign starts a tag, so an encoder replaces < with &lt;. The browser then shows the reader a literal less-than sign instead of opening a tag.

Notice what escaping does not do: it does not decide whether the data is good or bad, and it does not remove anything. A comment that says I <3 this still says that after encoding; it is simply represented so the browser will not mistake the < for markup. That distinction matters, because many security bugs come from treating escaping as a filter that cleans input, when it is really a translator that preserves meaning across a boundary.

The contexts, and why one encoder is not enough

Consider the string "><script>alert(1)</script>. In plain HTML text, escaping <, >, and & is enough to neutralize it, because those are the characters that let text become markup. But place the same string inside an attribute, a URL, or a script block, and different characters become dangerous:

Context What is dangerous Correct approach
HTML text content <, >, & HTML-entity encoding: < becomes &lt;, and so on
HTML attribute value Quote character that closes the attribute, plus & Attribute encoding with the matching quote encoded; prefer double-quoted attributes
URL / query parameter &, =, ?, #, spaces, non-ASCII Percent-encoding of the parameter value (%26, %20, etc.)
JavaScript string Quote, backslash, line breaks, </script> JavaScript string encoding or, better, a safe JSON serializer plus HTML encoding of the block
CSS value Characters that end the value or start a new rule CSS escaping; avoid placing untrusted data in CSS at all
SQL query Quote characters that end a string literal Do not escape by hand — use parameterized queries / prepared statements

The key insight: an encoder for one row of this table does not protect the other rows. HTML-entity encoding a value and then dropping it into a JavaScript string is a classic failure, because the browser’s HTML parser decodes entities before the JavaScript engine sees the string. The JavaScript engine then receives the original dangerous characters, unprotected. Encoding must match the final context where the data is interpreted, not an intermediate one it passes through.

Worked example: one username, five contexts

Suppose a user chooses the display name Alex "AJ" O’Neil <admin>. It contains a double quote, an apostrophe, an ampersand, and angle brackets — a good stress test. Here is how it should appear in each context:

  • HTML text: Alex &quot;AJ&quot; O’Neil &lt;admin&gt;. The reader sees the name exactly as typed, and no tag is created.
  • HTML attribute: <span title="Alex &quot;AJ&quot; O’Neil &lt;admin&gt;">. The double quotes inside the value are encoded so they cannot close the attribute early and inject a new attribute such as an event handler.
  • URL query value: ?name=Alex%20%22AJ%22%20O%E2%80%99Neil%20%3Cadmin%3E. Percent-encoding stops the ampersand and other characters from being read as parameter separators.
  • JavaScript string: the name should be inserted via a JSON serializer that escapes quotes, backslashes, and control characters, and the enclosing script block should not be built by string concatenation. Hand-rolling this with a few replacements is how bugs are born.
  • SQL: the name should be passed as a bound parameter, never interpolated into the query string. Parameterization separates code from data at the database level, which is stronger than any escaping scheme.

Now watch what happens when the contexts are mixed up. If the URL-encoded form is placed directly into HTML text, the reader sees the ugly percent-encoded string instead of the name — a display bug, not a security hole. If the HTML-encoded form is placed into a JavaScript string, the browser decodes the entities first, and the script engine sees the raw quote and angle brackets — a real vulnerability. The same data, the same encoder, two different outcomes, decided entirely by context.

How to encode correctly: a checklist

  1. Encode at output, not at input. Store the original data, and encode it each time it is rendered into a specific context. Encoding on input destroys information — you can no longer tell what the user actually typed — and the stored encoding will be wrong for at least one future context.
  2. Ask “where does this value end up?” for every variable. A template variable might appear in HTML text in one place and in an attribute in another. Each occurrence needs its own encoding, matched to its own context.
  3. Use the framework’s encoder for that context. Prefer framework auto-escaping and safe templating helpers over hand-written replacement tables. A template engine knows which context each variable is in and applies the right encoder; a hand-written replace function only knows the cases its author remembered.
  4. Never build code by concatenating untrusted strings. No amount of escaping makes string-built SQL, shell commands, or script blocks as safe as parameterized APIs. Escaping is a last line of defense for display; structured APIs are the real boundary.
  5. Review the final rendered context rather than only the source string. View the page source, inspect the attribute values, and test with adversarial inputs that include quotes, angle brackets, ampersands, and Unicode. A value that looks safe in your source file may be decoded one extra time by the browser before it is interpreted.

Sanitization is not encoding

Treat sanitization and encoding as different actions. Sanitization decides what is allowed; encoding changes how allowed data is represented in a context. A sanitizer might strip all HTML tags from a comment, or allow only a small set of safe tags such as <b> and <a>. An encoder takes whatever survived and represents it safely in HTML, a URL, or JavaScript.

Confusing the two produces two kinds of failure. Sanitizing where encoding was needed removes content users legitimately typed — a math comment saying “a < b” loses its meaning if the sanitizer eats it. Encoding where sanitization was needed preserves an attack: encoding a malicious link’s text does nothing about the fact that the link’s destination is a javascript: URL. If your feature accepts rich content, you need both: a sanitizer that enforces an allow-list of tags and attributes, and an encoder that represents the result safely in its context.

Double encoding and other traps

  • Double encoding: encoding an already-encoded value turns &lt; into &amp;lt;, which the reader sees as the literal text &lt; instead of <. This is usually a display bug caused by encoding twice — once manually and once by the framework. If you see entity names on screen, something encoded twice.
  • Encoding too late: encoding a value after it has already been inserted into a URL or a script means the dangerous interpretation already happened. Order matters: encode, then insert.
  • Trusting innerHTML: assigning untrusted data to innerHTML asks the browser to parse it as markup, which defeats encoding done for a text context. Use textContent or a safe templating API for untrusted text.
  • Allowing javascript: URLs: an encoded URL is still dangerous if its scheme executes code. Validate URL schemes against an allow-list (https:, http:, mailto:) before rendering links.
  • Forgetting attribute contexts in event handlers: values inside onclick and similar attributes pass through HTML parsing and then JavaScript parsing, so they need both layers handled. The safest fix is to avoid inline event handlers and attach listeners from script instead.

Limitations

This guide explains the principle and the most common contexts. It is not a complete security reference: real applications also need Content Security Policy headers, modern framework defaults, dependency hygiene, and testing with dedicated security tooling. Context-specific encoding is one layer of defense, not a guarantee, and it does not fix flaws such as broken access control, insecure direct object references, or unsafe deserialization. For anything that handles credentials, payments, health data, or user-generated content at scale, have the implementation reviewed by someone who specializes in application security before relying on it.

Frequently asked questions

If I HTML-escape everything, am I safe from cross-site scripting?

Not on its own. HTML escaping protects HTML text and, with quote handling, attribute values. It does not protect JavaScript strings, CSS, URLs, or SQL, because those languages interpret the decoded value with their own rules. You need the right encoding for each context, plus sanitization where rich content is allowed, and ideally a Content Security Policy as an additional layer.

Should I escape data when I save it to the database?

No. Store the original data, and use parameterized queries so the database never confuses data with SQL. Escape at output, when you know the destination context. Escaping on input bakes one context’s encoding into the stored value, which will be wrong for every other context and can corrupt legitimate content.

Why does my page show &amp; instead of &?

That is double encoding: the value was encoded twice, so the browser displays the entity for an ampersand rather than the ampersand itself. Find the extra encoding step — often a manual escape on top of a framework’s auto-escaping — and remove it. Encode exactly once, at the point of output, in the final context.

Is innerText or textContent safer than innerHTML?

Yes, for untrusted text. Assigning to textContent inserts the value as text, so markup characters are never parsed as HTML. innerHTML parses its input as markup, so it should only ever receive trusted, sanitized HTML — never raw user input.

Use the related tool carefully

This guide is paired with a browser-only utility. The tool is a practical aid for small examples and inspection; it is not a substitute for application testing, a formal data pipeline, or professional review where the decision has higher consequences.

Open the related HTML Entity Encoder and Decoder

Related tools in this category

Sources