TL;DR / Summary: Entity escaping is an output decision, not an input cleanup step. Escape the five characters that can change markup at the moment you render, keep the raw text in storage, and never run the escaper twice. Most “broken layout” bugs are a template that escaped once and then handed the string to something that escaped again.
What a browser does with a bare ampersand
HTML has a small set of characters that change how the parser reads the surrounding text. An ampersand starts a character reference, a less-than sign starts a tag, and a quote can end an attribute value early. Everything else a user types is displayed as written.
When a support form stores “Tom & Jerry <3" and the page later prints it raw, the browser tries to parse an entity after the ampersand. Depending on what follows, the visible result ranges from a missing fragment to a completely restructured paragraph.
The fix is not to strip the characters. Users are allowed to type an ampersand. The fix is to represent it in the markup as something the parser will read as data rather than syntax.
The five characters that actually matter
In element content you need the less-than sign and the ampersand. In attribute values you also need both quote styles, because either can delimit the attribute. The greater-than sign is technically safe in text but escaping it keeps the transformation symmetrical and easier to test.
- < for the less-than sign
- > for the greater-than sign
- & for the ampersand, always first in any replace chain
- " for a double quote inside a double-quoted attribute
- ' for an apostrophe inside a single-quoted attribute
Order matters in a naive replace chain. Replace the ampersand before the others, or every entity you just inserted will itself be escaped and the page will display the entity text instead of the character.
Quotes inside attributes
An attribute is only safe if the delimiter cannot appear in the value. If you build a link with a double-quoted href and insert a user-supplied URL, a double quote in that URL ends the attribute and lets the rest become new markup. Escaping quotes closes that path, but validating the URL scheme is still required.
Escape once, on output, not on input
Storing escaped text in a database looks convenient until the same value is needed in a JSON API, a CSV export, or a plain-text email. You then have to guess how many times the value was escaped before you can use it.
Keep the raw string. Escape at the boundary where it becomes HTML, and make that boundary a single function that every template calls. When the escaper lives in one place, a missing call is a review comment instead of a mystery in production.
Data keeps its original shape. Only the view changes clothes.
Template engines usually escape by default and require an explicit “safe” marker to skip it. If your code uses that marker in more than a couple of carefully reviewed places, treat each one as a place where injection can return.
Rich text is a different problem
Escaping is the correct answer for plain text and the wrong answer for a field that is supposed to contain formatting. If you escape a comment that allows bold and links, users see the tags instead of the formatting.
Rich fields need a parser that builds an allowlist tree, drops unknown elements, and rewrites unsafe attributes. Escaping at the end of that pipeline would undo the sanitising work. Decide which kind of field you have before choosing a library.
A common compromise: store both the rendered markup version and a plain-text version. The plain-text copy powers search, summaries, and notification emails without a second escaping debate.
Checking a payload before it ships
Paste a sample value into an encoder tool and read the output slowly. A correct escape of <img src=x onerror=alert(1)> begins with an escaped less-than sign and contains no raw angle brackets anywhere. If you still see a raw tag, the tool did not escape and probably just displayed the input.
Test the awkward characters, not only the obvious ones. Curly quotes, non-breaking spaces, and emoji survive many test suites and then break a layout on the one page nobody checked. The developer tools at Masters Tool include an entity encoder that shows the exact bytes, which is the fastest way to see whether double escaping happened.
Run the same value through the template twice and compare. Identical output means the transform is idempotent and likely missing. Different output means you found the second escape.
Where entity escaping does not help at all
Escaping stops HTML injection and nothing else. It does not make a URL safe to put in an href, it does not stop JavaScript inside an event handler you wrote yourself, and it does not protect a value inserted into a script block as JSON.
For script contexts, serialise the data as JSON and let the runtime parse it. For URLs, parse and check the scheme against an allowlist. For CSS, avoid interpolating user input entirely. Each context has its own grammar, and one escaper cannot satisfy all of them.
The same value moving into an email subject or a log line needs re-encoding for that medium. Reusing the HTML form there produces visible entities in inboxes and makes log searches fail on punctuation.
Signs your template layer already double-escapes
The page shows text like “Tom & Jerry” where the source only had one ampersand. Search results display entity names instead of punctuation. A CSV export looks correct while the web page looks wrong, or the reverse.
Grep for two escape calls in the same render path, and check whether a helper escapes before a template engine escapes again. Fix the pipeline, not the individual strings: hand-editing stored values to compensate will break the next feature that reads the same column.