Explain Codes LogoExplain Codes Logo

Do I encode ampersands in <a href...>?

html
encoding
web-development
best-practices
Nikita BarsukovbyNikita Barsukov·Aug 11, 2024
TLDR

Yes, you encode ampersands in URLs as &amp; for HTML validity. Here's the correct use:

<a href="https://example.com/?foo=1&amp;bar=2">Valid Link</a>

When it comes the necessity to encode, it's not just about what the browsable interface allows, but also about ensuring validity and proper interpretation of your HTML code. So, follow the standards and escape & as &amp;.

HTML ampersand encoding fundamentals

Ampersands (&) start HTML entities. When not encoded, they may confuse your HTML validator, the browser, or even the server processing the URL query parameters. Therefore, encode ampersands as &amp; within HTML attributes, especially in URLs to ensure proper interpretation and validity.

Quotation marks and non-ASCII characters

Double and single quotes should be also encoded within HTML attribute values. As for non-ASCII characters, such as é, ä, ç, or 你, these are best percent-encoded as per the RFC 3986 when they're part of a URL.

Prevention against double encoding

Be sure not to fall into the trap of double encoding. You don't want your & to turn into &amp;amp;. Over-encoding happens when you encode already encoded URLs, so verify your output to avoid such ambiguities.

Dynamic HTML ampersand encoding awareness

When dealing with dynamic URLs, often in JavaScript or JSON contexts, be cautious about applying the appropriate encoding and escaping. Automated tools and tests can help catch discrepancies during development.

Uniformity and adherence to guidelines

Maintaining a consistent coding style aids readability and error prevention. Always escaping ampersands in HTML attributes not only helps keep your code consistent, but also aligns with good web development practices and standards adherence.

Verifying the encoding correctness

HTML validators and browser developer tools aid in ensuring your code is correctly encoded and compliant with the set rules. These can save you from a myriad of cross-browser quirks and SEO impediments.

Benefits of encoding

Proper character encoding does more than just prevent errors:

  • Interoperability: Encoded URLs work across multiple systems, platforms, and browsers.
  • Improves Accessibility: Assistive technology users have an improved experience.
  • Better SEO: Search engines can index correctly encoded links better.