Explain Codes LogoExplain Codes Logo

Why shouldn't ' be used to escape single quotes?

html
character-references
html-entities
css-properties
Anton ShumikhinbyAnton Shumikhin·Nov 5, 2024
TLDR

When it comes to HTML escaping, stick with ' for single quotes as ' is not universally supported. Observe this quick substitution:

<p>It's a great day!</p>

flips to

<p>It&#39;s a great day!</p>

The outcome is, as you guessed it: It's a great day!

Diving into quote escapement

HTML provides a set of character references to objectify special characters or those that are elusive in HTML representation. Safer choices are numeric entities - &#39; for single quotes (apostrophe) and &#34; for double quotes.

Picking the appropriate quote entity

While HTML5 deems &apos; as valid, retaining legacy support (HTML 4 and XHTML) calls for named entities &lsquo; and &rsquo; for left and right single curved quotes respectively. Double quotes can enjoy &ldquo; and &rdquo;.

Coding semantically with quotes

For semantic correctness, <q> tags are used to symbolize short quotations which by default, will get rendered with suitable quotation marks by browsers.

Escaping quotes in older browsers

A noteworthy kiey point to remember is to confirm the compatibility of various escape sequences. It's possible some ancient browsers will not recognize &apos;, hence &#39; assures maximum compatibility.

Styling quotes with CSS

Leverage the power of CSS to handle quotation marks in your content - the quotes property can be your go-to tool for multilingual typesetting of quotations with varying quotation marks.

q { quotes: "‘" "’" "“" "“"; }

Encoding curly single quotes

There are times when you need to embed curly single quotes into your HTML. Turn to &#145; for left curly single quotes or opening apostrophes and &#146; for right curly single quotes or closing apostrophes.

XML vs HTML: their relation

Named character references significantly impact XML applications. Here, &apos; plays a notable role, but carries a different understanding in HTML 4. Always stay updated with the relevant specification (HTML vs XML) to avoid unusual outcomes.

Compatibility caution with XHTML

If XHTML is a part of your project, take note of Wikipedia's caution to abstain from using &apos;. As XHTML is an application of XML, but often served with MIME type text/html, potential confusion or compatibility issues may arise.