How to use ampersands in HTML: to encode or not to encode? – Peter Coles

How to use ampersands in HTML: to encode or not

to encode?

In HTML, the ampersand character (“&”) declares the beginning of an entity reference (a special character). If you want one to appear in text on a web page you should use the encoded named entity “&”—more technical mumbo-jumbo at w3c.org. While most web browsers will let you get away without encoding them, stuff can get dicey in weird edge cases and fail completely in XML.

This seems like a simple rule, but what about urls in HTML, javascript files, javascript in HTML, etc… Here’s a little guide to help clear up that ampersand HTML confusion:

Text in HTML:

<p>

Jack

&amp;

Jill ran up the hill.

</p>

A link in HTML (or any HTML attribute value):

<a

href=

"http://lmgtfy.com/?l=1&amp;q=rick+roll"

>

tired meme

</a>

Note: Matt describes in the comments below the difference between escaping an & to split up query string parameters and percent escaping one to be in the value of a query string parameter.

A link in javascript:

window

.

location

=

'http://lmgtfy.com/?l=1&q=rick+roll'

;

If you’re using a web framework that escapes variables for you and you pass in a url as a variable into javascript, then you’ll have to make sure it doesn’t encode the ampersands. In Django, you would write something like this: window.location = '{{ url|escapejs }}';

Also, if this is inline javascript—in an HTML document, not a separate .js file—then you still shouldn’t escape the ampersand, which means the document will not validate as XHTML. Either throw it into a separate .js file or stop worrying so much about validating your code.

Inside an onclick in HTML:

<a

href=

"#"

onclick=

"window.location='?l=1&amp;q=rick+roll';return false"

>

kablammo!

</a>

This is redundant to the second example, but worth pointing out since it’s javascript inside an attribute of an HTML tag.

Dynamically in Javascript (example using jQuery):

$

(

'#result'

).

text

(

'Jack & Jill'

);

// .text() escapes the text for you

$

(

'#result'

).

html

(

'Jack &amp; Jill'

);

// .html() sets the HTML directly

document

.

getElementById

(

'result'

).

innerHTML

=

'Jack &amp; Jill'

;

In a Tweet

When

to

use

&

and

when

to

use

&

amp

;

amp

;

http

:

//

bit

.

ly

/

dtiumF

Twitter auto-converts encoded ampersands…

Some extra notes:

  • If you want to use an ampersand as a value inside the query string of a url (and not as a delimiter for separating arguments), then you should use the URL-encoded value: %26
  • Quotes should be encoded too (&quot;), but I prefer to use utf8 curly quotes
  • The other main characters to remember to encode are < (&lt;) and > (&gt;), you don’t want to confuse your browser about where HTML tags start and end