Why encode text for HTML
Some characters have a meaning in HTML. A < starts a tag and an & starts an entity. If you put them in a page as they are, the browser tries to read them as markup. Encoding replaces them with entities, so they are shown as characters. This is how you display code in a page, and it is a basic defense against cross-site scripting (XSS) when you show text from users.
What to encode
| Option | Encodes | Use it for |
|---|---|---|
| Text content | & < > | Text between tags, such as inside a p or a div |
| Attribute values | & < > " ' | Values inside quotes, such as title or alt. The default. |
| All non-ASCII characters | The above, and every character above code 127 | Pages or systems that are not set to UTF-8 |
| Every character | Everything except spaces and line breaks | Obscuring an email address from simple scrapers |
Entity styles
- Named:
é,©. Easy to read. Characters that have no name fall back to the decimal form. - Decimal:
é. Works for every character. - Hex:
é. The same as decimal, and it matches the Unicode code point.
The apostrophe
The apostrophe is written as ' by default, because it works everywhere. ' is valid in HTML5 and XML, but very old browsers did not know it, so choose it only if you need it.
Avoid double encoding
Encoding & a second time gives &amp;, and the page shows the code and not the character. Tick Leave existing entities alone when your text may already contain entities.
Other options
- Line breaks: keep them, or turn each one into a <br> tag.
- Emoji and other characters above U+FFFF are encoded as one entity, such as
😀, and not as two broken halves.
Know the limits
HTML encoding is right for HTML text and attribute values. It is not enough inside a script, a style block or a URL, which each need their own kind of escaping. The HTML entities guide explains this and shows how to encode in PHP, JavaScript and Python.
To reverse the result, use HTML decode. Look up names in the HTML entities list, or convert entities to other formats with the entity decoder and converter. You can also tidy the result with the HTML formatter.