Writing Valid XHTML links using Ampersands

URL links on web pages often include the ampersand ("&") but that isn't valid XHTML. It isn't hard to fix though. Here is how.

Ampersands are used in URL strings to send sets of variables along with the URL post to tell the web server more about what it is you are asking for. Consider this example:

<a href="http://www.blogger.com/post-edit.g?blogID=19459839">Edit this post</a>

In this example, clicking on this URL says that you want to use the "edit" command on Blogger to edit a post on blog number "19459839" and on that blog the post you want to edit is post number "8950573203392784572". The ampersand is read as "and" - you want to open an edit window for a certain blog and a certain blog post.

All well and good but the page is no longer valid XHTML because of that pesky ampersand. That just isn't valid XHTML.

This is easy enough to fix though. The trick is to use the proper XHTML substitute. In this case it is to replace the "&" with "&amp;". Note that the substitute is 4 characters and that the last character is the semi-colon.

That makes the XHTML code in your page look like this:

<a href="http://www.blogger.com/post-edit.g&amp;blogID=19459839">Edit this post</a>

The URL still works as before and it is probably rendered by your browser as an "&" symbol - i.e. if you hover your mouse over the link you will still see "&" not "&amp;" but the underlying code (what you would see using "View Source" in your browser) still uses the "&amp;".

Do this and you will have valid XHTML easy enough.

No comments: