Explain Codes LogoExplain Codes Logo

How can I escape a single quote?

html
html-entities
character-references
html-preprocessing-errors
Anton ShumikhinbyAnton Shumikhin·Feb 10, 2025
TLDR

To escape a single quote in HTML, use the entity '. For example:

<p>Bob&#39;s burgers - Ensure your friendships with vegans are well done!</p> <!-- A vegan-friendly joke, everyone! -->

It will display as: Bob's burgers - Ensure your friendships with vegans are well done!

When you need a single quote within an attribute, use double quotes for the attribute and then use the entity. For instance:

<a href="javascript:void(0)" onclick="alert('Bob&#39;s burgers are delicious.');">Try me</a> <!-- Humor tastes better with burgers -->

Escaping characters - The when and why?

HTML entities, also known as character references, come into play in two main scenarios:

  1. Within an attribute: If you need to embed a quote (single or double) inside an attribute value.
  2. In the document body: When you need to represent characters that hold special meanings in HTML syntax, or are not easily represented in your document's character encoding.

Escaping these characters helps avoid syntax errors and maintains the correct display of characters in your HTML code.

What to escape? Engaging the escape artist within

Common characters in HTML that you need to escape include:

  • Double quote (") => &#34; or &quot;.
  • Greater than (>) => &#62; or &gt;.
  • Less than (<) => &#60; or &lt;.
  • Ampersand (&) => &#38; or &amp;.

With these you can eliminate potential HTML preprocessing errors and display special characters correctly.

Compatibility quirks and internet explorer's infamous reputation

While HTML entities are universally supported, there are exceptions to the rule:

  • &apos; for single quotes in HTML attributes isn't always recognized in older versions of Internet Explorer. &#39; or &#x27; is a safer choice.
  • For the latest and most broadly supported escape sequences, consider the W3C HTML5 Named Character References.

Developer cheat sheet: Handy escapes for the win

  • Numeric entities (&#39;) have wider browser support over named entities (&apos;).
  • Check your webpage across different browsers to ensure that all entities are displayed correctly - better safe than sorry!
  • For dynamic content, escape characters programmatically using server-side functions like htmlspecialchars() in PHP or String.prototype.replace() in JavaScript.

Pitfalls and how to dodge them

Encoding errors often occur when characters aren't escaped correctly. These can manifest as:

  • Characters not displaying correctly - the entity is possibly not recognized.
  • JavaScript errors due to an unescaped quote in inline event handlers.

To solve these issues:

  • Use validation tools like the W3C Markup Validation Service to discover and rectify errors.
  • Consider implementing unobtrusive JavaScript – separate behavior from your content layer to minimize encoding errors.