FileGizmo glossary

HTML entity

An HTML entity writes a character as a short code beginning with an ampersand and ending with a semicolon. It exists so that characters with meaning to a parser, such as the angle brackets around a tag, can appear as text without being read as markup.

An HTML parser reads certain characters as instructions. An angle bracket starts a tag, an ampersand starts an entity, a quote mark ends an attribute value. Text that contains those characters and means them literally needs a way to say so.

An entity is that way. It begins with an ampersand, names or numbers the character, and ends with a semicolon.

The five that matter

In practice five characters need escaping in a document declaring UTF-8: the ampersand, the two angle brackets, and both quote marks.

Escaping everything above ASCII as well was standard when encodings were unreliable and a stray byte rendered as a question mark. It still appears in older pipelines. The cost is that a paragraph of Greek, Japanese or Arabic becomes a run of numeric codes nobody can proofread, and it buys nothing in a document that has declared its encoding.

Named, decimal and hexadecimal

A named entity spells its character. A numeric one gives the code point, in decimal or in hexadecimal. Numeric entities can express any character; named ones exist only for a fixed list.

Real documents contain all three, often in the same file, because they have usually passed through more than one system.

The mistake worth avoiding

Escaping and sanitising answer different questions, and treating one as the other is a genuine security bug rather than a stylistic one.

Escaping takes text and makes it safe to display as text. Every character survives and none of it is interpreted. Sanitising takes markup and decides which parts of it are allowed to remain markup, which is a much harder problem involving tags, attributes, URLs and styles.

If what you have is text that will be displayed, escape it. If what you have is markup from somebody else that you intend to render as markup, escaping it will show the tags rather than apply them, and what you actually need is a sanitiser.

Frequently asked questions

Which characters have to be escaped?

Five, in practice. The ampersand because it starts an entity, the two angle brackets because they delimit tags, and both quote marks because they delimit attribute values. Everything else is optional in a document declaring UTF-8.

What is the difference between named and numeric entities?

A named entity spells the character, as in &. A numeric one gives its code point in decimal or hexadecimal. Numeric works for any character; named only for those that have a name.

Is escaping the same as sanitising?

No, and confusing them is a real security mistake. Escaping makes text safe to display as text. Sanitising decides which markup to allow through. If you are accepting markup rather than text, escaping is not the tool.