HTML Comments, Entities, and Character Encoding: The Details That Prevent Silent Bugs

HTML entities, comments and UTF-8 explained: when to escape characters, ampersands in URLs, non-breaking spaces, comment pitfalls, and fixing mojibake.

Executive Summary: With UTF-8 declared correctly, you only need entities for a handful of characters: < and & in text, and quotes inside attribute values. Most other entities are habits from the days of mixed encodings. The bugs that remain come from encoding mismatches that turn “café” into “café”, invisible characters pasted from documents, ampersands in URLs, and comments that leak information to anyone who views the source.
Large ampersand entity next to code showing escaped characters and a UTF-8 meta tag

A customer named Renée signs up, and her welcome email greets “Renée”. A product page shows “Don’t miss out” in the hero. A pricing table breaks onto two lines between “₹” and “499”. A search box fails to match a product name copied from a spreadsheet, because it contains a zero-width space nobody can see. None of these throws an error. They just ship.

This article covers the three low-level details that cause them. Character encoding is the mapping from bytes to characters, and on the web it should always be UTF-8. HTML entities, or character references, are escape sequences like & that let you write characters the parser would otherwise treat as markup. What should HTML comments never contain? are text the browser ignores but anyone can read. Get these right once and an entire class of silent bugs disappears.

How should you declare UTF-8?

UTF-8 can encode every Unicode character, from Latin letters to Devanagari, Arabic, CJK and emoji. It is what the HTML specification requires for new documents and what over 97% of websites use, according to W3Techs. The browser needs to know the encoding before it decodes the page, and it gets that information from, in order of priority:

  1. A byte-order mark at the very start of the file, if present.
  2. The charset parameter of the HTTP Content-Type header.
  3. A <meta charset="utf-8"> within the first 1024 bytes of the document.
  4. A guess, based on locale and content sniffing.

Set both the header and the meta tag, and make sure the meta tag is the first element in the head. Then make sure the bytes really are UTF-8. Declaring UTF-8 does not convert anything; it only tells the browser how to read bytes that must already be UTF-8.

How does mojibake happen?

“Mojibake” is garbled text caused by decoding bytes with the wrong encoding. The character “é” in UTF-8 is two bytes, C3 A9. Read those two bytes as Windows-1252 or ISO-8859-1, and you get two characters: “é”. A curly apostrophe is three UTF-8 bytes, which become “’” in Windows-1252.

You see Should be Usual cause
é, ñ, ü é, ñ, ü UTF-8 bytes read as Latin-1 or Windows-1252
’, “, … ’, “, … Same, for punctuation pasted from word processors
é é Text converted to UTF-8 twice
� (replacement character) Any non-ASCII character Latin-1 bytes read as UTF-8

The fix is almost never in HTML. Check, in order: the file’s actual encoding in your editor, the HTTP header from the server, the database column and connection encoding (MySQL’s utf8 is a three-byte subset that cannot store emoji; use utf8mb4), and any API or CSV import step that reads bytes without stating an encoding.

Which HTML entities do you actually need?

A character reference starts with & and ends with ;. It can be named (&copy;), decimal (&#169;) or hexadecimal (&#xA9;). With UTF-8, you can type ©, ₹, é or → directly, so most named entities are unnecessary. The ones you still need exist because of HTML syntax, not encoding:

Character Entity When you must escape it
< &lt; In text, whenever it could start a tag, such as code samples
& &amp; In text and attributes, whenever it could start a character reference
" &quot; Inside attribute values delimited by double quotes
' &#39; Inside attribute values delimited by single quotes
> &gt; Rarely required, but escape it in code samples for symmetry

When displaying user-supplied content, escaping is not optional and is not something to do by hand. It is your template engine’s job, and it is what prevents cross-site scripting. Every mainstream engine escapes by default; the danger is the escape hatch, such as dangerouslySetInnerHTML in React, {!! !!} in Blade or |safe in Jinja, and any code that builds HTML with string concatenation and innerHTML. Use textContent when inserting text with JavaScript.

Ampersands in URLs

<a href="/search?q=shoes&amp;sort=price">Shoes by price</a>

In attribute values, a bare & followed by letters can be read as the start of a named reference. Browsers have legacy rules that make &sort= work, but a parameter named copy, reg or not can be decoded into ©, ® or ¬ in some contexts. Write &amp; in the HTML; the browser turns it back into & before requesting the URL. The validator flags every bare ampersand, which makes it easy to find them all.

What kinds of spaces exist in HTML?

Character Code point Use
No-break space, &nbsp; U+00A0 Keep two words together: ₹&nbsp;499, 10&nbsp;km, Mr.&nbsp;Rao
Narrow no-break space U+202F Between numbers and units in some style guides, and inside French punctuation
Soft hyphen, &shy; U+00AD An optional hyphenation point in long words
Zero-width space U+200B An optional break point without a hyphen; prefer <wbr> in HTML
Zero-width joiner U+200D Joins emoji sequences and is required in some scripts; never strip it blindly

Use &nbsp; for its real purpose, preventing a line break, not for indentation or spacing between elements. A row of &nbsp;&nbsp;&nbsp; for layout is announced by some screen readers and breaks at different widths. Use CSS margins or gap.

Invisible characters are the source of the strangest bugs: a zero-width space in a product SKU that breaks exact-match search, a non-breaking space in an email address that fails validation, a byte-order mark at the start of an included PHP file that adds a blank line above the doctype. Normalize user input on the server by trimming, converting non-breaking spaces where they are not wanted, and stripping zero-width spaces from identifiers. In your editor, turn on visible whitespace and a “highlight unusual characters” setting. VS Code highlights ambiguous and invisible Unicode characters by default.

Comments

<!-- Primary navigation. Items come from the CMS menu "main". -->

HTML comments start with <!-- and end with -->. A few rules and habits keep them harmless:

  • They are public. Everything in an HTML comment is sent to every visitor. Never leave credentials, internal hostnames, ticket links, disabled feature names or notes like “TODO: fix auth bypass” in markup. Use template-language comments, such as {# #} in Twig and Jinja or {{-- --}} in Blade, which are stripped on the server.
  • They cannot nest. The first --> ends the comment, so commenting out a block that already contains a comment leaves the rest visible on the page.
  • Avoid -- inside comment text. It is a parse error in some positions and confuses tools.
  • Conditional comments are dead. <!--[if IE]> only worked in Internet Explorer 9 and earlier. Delete them.
  • They still cost bytes. HTML minifiers strip them in production builds, except comments some frameworks use as hydration markers. Check before enabling aggressive minification on a server-rendered React or Vue app.

A checklist for new projects

  1. Save every source file as UTF-8 without a byte-order mark.
  2. Send Content-Type: text/html; charset=utf-8 from the server.
  3. Put <meta charset="utf-8"> first in the head, as covered in the HTML5 document guide.
  4. Use utf8mb4 for MySQL and MariaDB tables and connections.
  5. Let the template engine escape output; audit every place that bypasses it.
  6. Write &amp; for ampersands in attributes and run the validator.
  7. Keep secrets and internal notes in server-side comments only.

Frequently Asked Questions

Do I still need HTML entities if my page is UTF-8?

Only for characters that HTML syntax treats specially: < and & in text, and quotes inside attribute values. Other characters such as ©, ₹, é and emoji can be typed directly in a UTF-8 document.

Why does my text show characters like é or ’?

Those are UTF-8 bytes being decoded as Latin-1 or Windows-1252. Check the file’s real encoding, the server’s Content-Type header, the database and connection encoding, and any import step that reads text without specifying UTF-8.

Should ampersands in URLs be written as &amp; in HTML?

Yes. Inside href and other attributes, write &amp;. Browsers decode it back to a plain ampersand before requesting the URL, and escaping avoids parameters being misread as named character references.

Are HTML comments visible to users?

They are not displayed on the page, but they are sent to every visitor and anyone can read them with View Source. Keep sensitive notes in server-side template comments, which are removed before the HTML is sent.

Small details, real bugs

Encoding and escaping feel like solved problems right up until a customer’s name is garbled in an invoice. Declare UTF-8 early, make the bytes match the declaration, escape the few characters HTML cares about, and keep your comments boring. The same principle applies to how the parser handles invalid nesting: the browser does exactly what the bytes say. For the full reference, see the named character references table in the HTML Standard and the W3C guide to declaring character encodings. Related reading on this site: semantic HTML explained.

Originally posted on 14 March 2023 and post last modified on 14 March 2023

Character Encoding Front-End Development HTML Entities HTML5 UTF-8

Share this article

Leave a Reply

Your email address will not be published. Required fields are marked *