🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

HTML Encoding, Entities, and Safe Escaping

Web FoundationsEncoding🟢 Free Lesson

Encoding, Entities, and Safe Escaping

The word encoding covers three unrelated jobs in a browser, and conflating them produces bugs that look identical from the outside: a page shows the wrong characters, a script inserts text that vanishes, or a value arrives at the server mangled. The three jobs are character encoding, which maps bytes to characters; markup escaping, which stops text from being interpreted as tags; and transport encoding, which makes arbitrary bytes safe inside a URL or a header.

Character encoding is decided once per document. The declaration must appear within the first kilobyte of the file or the browser may start parsing with the wrong assumption, which is the classic cause of a page where every accented letter has been replaced by a placeholder sequence. UTF-8 has won this argument: it represents every character in Unicode, it is ASCII-compatible for the first hundred code points, and it has no byte-order ambiguity in practice.

Markup escaping is a separate discipline that applies to text based on where it is going rather than on what it contains. The rules differ for element content, attribute values, and script blocks, and the difference is the source of most injection bugs:

  • in element content, ampersand, less-than and greater-than need escaping
  • in a quoted attribute value, the quote character of that attribute is the dangerous one
  • in an unquoted attribute value, whitespace and several punctuation characters terminate the value early, which is why unquoted attributes should be avoided entirely
  • in a URL parameter, escaping the markup characters is not enough; the value must also be percent encoded
  • in a JavaScript string inside a script block, the sequence that opens a closing script tag must be broken up or the HTML parser ends the block before the JavaScript parser sees it

The Characters You Cannot Type Directly

Some characters have meaning to the HTML parser before any of your styles or scripts run. Representing them through a character reference removes the ambiguity, and both the named and the numeric forms are valid.

CharacterNamed referenceNumeric referenceWhy it needs an escape
Ampersand&&Starts every other reference, so a bare one corrupts them
Less-than<<Opens a tag or a comment
Greater-than>>Closes a tag; rarely dangerous alone
Double quote""Ends a double-quoted attribute
Single quote''Ends a single-quoted attribute
Non-breaking space  Prevents a line break at a fixed point
Em dash——Typographic separation with no keyboard key

Numeric references come in two flavours: a decimal value such as — and a hexadecimal value such as —, which produce the identical character. Both may take a trailing semicolon, though the semicolonless form is tolerated only for a small historical list of named references. Writing the semicolon form everywhere costs nothing and removes an entire class of parser quirks.

Escaping Untrusted Text Before It Touches the DOM

The rule is simple: text goes in as text, never as markup. The browser provides the escape function for free through a temporary element, because assigning to textContent and reading back the innerHTML gives you exactly the serialization the parser expects.

javascript
function escapeHtml(value) {
  return String(value)
    .replaceAll('&', '&')
    .replaceAll('<', '&lt;')
    .replaceAll('>', '&gt;')
    .replaceAll('"', '&quot;')
    .replaceAll("'", '&#39;');
}

function escapeAttribute(value) {
  return escapeHtml(value).replaceAll('`', '&#96;');
}

const userComment = 'Nice try <img src=x onerror=alert(1)> & more';

document.getElementById('rendered').textContent = userComment;
document.getElementById('serialized').innerHTML =
  `<blockquote>${escapeHtml(userComment)}</blockquote>`;

const container = document.createElement('div');
container.innerHTML = `<p title="${escapeAttribute('He said "hello"')}"></p>`;

Order matters when you build the function by hand: the ampersand must be replaced first, or every later replacement introduces a new ampersand that the first pass already finished with. The same applies to building the string with a regular expression, which is why a chain of replace calls in the correct order is easier to reason about than one clever pattern.

🚨Escaping is not sanitizing

Escape when you intend to show text. Sanitize when you intend to allow a restricted subset of markup, and use a sanitizer written for that purpose; a hand-rolled allow-list that forgets one attribute will hand an attacker script execution.

What Happens When Encoding Goes Wrong

Two failure signatures are worth memorising because they point at opposite mistakes. A string of odd sequences with trailing bytes that resemble punctuation almost always means a UTF-8 file was decoded as Latin-1 somewhere in the pipeline. Question marks in place of accented characters usually mean a database column, a connection, or a response header declared a narrower charset than the data actually contains.

The fixes live in different places. The mojibake case is fixed by declaring UTF-8 consistently: a meta charset in the document, a charset parameter on the content-type header of every API response, and a UTF-8 encoding on the database connection. The replaced-character case is fixed by widening the column or the connection charset rather than by changing the page, because by the time the page renders, the original bytes are already gone.

A quick way to narrow it down is to encode a known string at each boundary and compare. Write the same accented text through the API, into the database, and out of the export, and find the first hop where the bytes change.

Percent Encoding and Base64 Are Not HTML Entities

Transport encoding answers a different question: how do I carry bytes that a URL, a header, or a JSON string cannot legally contain? Percent encoding replaces each disallowed byte with a percent sign followed by two hexadecimal digits, and it is the correct treatment for every character in a query parameter, not just the markup characters.

javascript
const query = 'search=café & "special"';

const url = new URL('https://example.com/find');
url.searchParams.set('q', 'café & "special"');
url.searchParams.set('page', '2');
console.log(url.toString());

const manual = encodeURIComponent(query);
console.log(manual);

const payload = btoa(unescape(encodeURIComponent('héllo — world')));
console.log(payload);
console.log(decodeURIComponent(escape(atob(payload))));

encodeURIComponent is the function to reach for inside a query string, and the URLSearchParams API shown first is better still because it handles the separators as well. Base64 is a third thing entirely: it packs arbitrary bytes into a sixty-four-character alphabet that survives email and JSON untouched, it is not encryption, and it inflates the size by about a third. Use it for binary attachments and for carrying structured values through systems that only pass strings.

Where Each Form of Escaping Belongs

The practical map from context to treatment is short enough to keep in memory. Static HTML in your own templates needs nothing, because you wrote it. Interpolated text in element content needs markup escaping. Values placed inside quotes need the quote of that attribute escaped as well. Query parameters need percent encoding through the URL API. JSON payloads need the serializer rather than any character replacement at all.

The mistake that causes incidents is applying the wrong map. Escaping a value for display and then reading it back out as data double-escapes it, so an ampersand becomes a visible entity in the next round trip. Escaping a value for storage fixes nothing, because the injection happens at render time, not at save time. Escape at the boundary where text changes role, and nowhere else.

Reading Values Back Out: The Decoder Runs for Free

Escaping is only half the cycle, and the decoding half is where round-trip bugs hide. When the parser builds the document, every character reference in the source is resolved once, so an attribute written with a reference contains the plain character when you read it. The three accessors then disagree deliberately: textContent returns decoded text, innerHTML returns serialized markup with entities re-escaped where the serializer deems it necessary, and getAttribute returns the decoded attribute value as the parser stored it.

That split produces the double-escape bug in practice. Code that reads innerHTML to extract a value and writes it back through innerHTML twice escapes any entity the serializer emitted, so a title containing an ampersand slowly accumulates entities with each edit-save cycle. Read with textContent and write with textContent for anything that is a value rather than a fragment.

The same principle governs form fields. A user who types an ampersand into an input gets an ampersand in value, because the input's value is data, not markup. Only when that data is later interpolated into an HTML string does it need escaping, which is precisely the boundary described below.

Common Mistakes

Escaping for storage instead of for output

Fix: Store the raw value and escape it in the template where it becomes markup; escaping earlier only guarantees double-escaped output later.

Building an escape function that replaces the ampersand last

Fix: Replace ampersands first, since every other replacement introduces new ones that a later pass would corrupt.

Relying on a meta charset declared after the first kilobyte

Fix: Put the charset declaration at the very top of the head so the parser never guesses.

Treating Base64 as a security measure

Fix: Base64 is an alphabet conversion, not encryption; use TLS and proper key management for confidentiality.

Key Takeaways

  • Character encoding, markup escaping, and transport encoding solve three different problems and have three different tools.
  • Escape ampersand first when writing an escape function by hand, or you will corrupt the replacements you already made.
  • Declare UTF-8 in the document, in every response header, and on the database connection, or the pipeline will mangle text you never touched.
  • Escape at the boundary where text changes role: to markup, to a URL, or to a JSON payload, but never to storage.
  • Escaping shows text literally; sanitizing allows a subset of markup. Reach for the right one deliberately.
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Web Development Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement