Search code examples
javascripthtmlhtml-entitiesweb-standardsstandards-compliance

XHTML/HTML/JS syntax: When do I use &?


I am confused when I should use & and when I should use &, specifically when it's inside Javascript inside HTML.

Which (or both or neither) of these two URLs should use html-encoding?

<!-- Example 1 -->
<script type='text/javascript'>
    var myUrl = "myurl.html?bob=2&mary=3"; // or is it &amp;?
    downloadUrl(myUrl);
</script>

<!-- Example 2 -->
<p>Click <a href="myurl.html?bob=2&mary=3">here</a> <!-- &amp;? --> if the download doesn't start.</p>

Solution

  • In HTML, you should use &amp; instead of &. In XHTML/XML, you must use &amp; instead of &. This also applies to inline JavaScript code. This doesn't apply to JavaScript code served by fullworthy .js files unless the text becomes part of the HTML DOM tree.