Guide
HTML entities and when to encode them
By Logappradeep · ServiceNow developer
HTML gives a few characters special meaning: < starts a tag, & starts an entity, and quotes delimit attribute values. To display those characters as literal text, you replace them with character references, commonly called HTML entities. Encoding <b>Tom & Jerry</b> produces <b>Tom & Jerry</b>, which a browser shows as the original text instead of rendering bold markup. This encoder converts &, <, >, double quotes, and apostrophes, and writes every non-ASCII character, such as é, as a decimal reference like é, so the output is plain ASCII that is safe in any document encoding.
Three ways to write the same character
- Named references such as
<,&,",©, and . - Decimal numeric references such as
<for<oréforé. - Hexadecimal numeric references such as
<oré.
All three decode to the same character. Numeric forms work for any Unicode code point, while named forms exist only for characters that have an assigned name in the HTML specification.
Where encoding is the right tool
- Showing code samples, error messages, or user-submitted text inside a web page.
- Writing content for CMS fields, email templates, or Markdown processors that pass raw HTML through.
- Embedding text in XML or RSS, which shares the same core entities.
- Decoding text from APIs or scraped pages that arrive full of
&and'.
Context is everything for security
Encoding user input before inserting it into HTML is a central defense against cross-site scripting (XSS), but only for the context it was designed for. Entity encoding protects text placed in element content and in quoted attribute values. It does not make data safe inside a <script> block, an inline event handler such as onclick, a CSS value, or a URL attribute, where a value like javascript:alert(1) contains no characters that HTML encoding would change. Each of those contexts needs its own escaping or, better, avoiding untrusted data there entirely. Modern frameworks such as React, Vue, and Angular escape text automatically, so manual encoding is mostly needed in templates, string concatenation, and legacy code.
Common mistakes
- Double encoding. Encoding text that is already encoded produces
&lt;, which shows up on the page as a visible<. Encode once, at output time. - Encoding on input. Storing HTML-encoded text in a database makes it wrong for every non-HTML use, such as JSON APIs, CSV exports, or SMS. Store raw text and encode when rendering.
- Unquoted attributes. In
<div class=VALUE>, a space in the value can start a new attribute. Always quote attribute values.
Encoding and decoding happen locally in your browser as you type, and decoding converts entities to plain text without rendering or running any markup.