XHTML compliant with ampersands in the URL

I was having a few problems creating a page with ampersands in the URL. This is a quick fix if it’s part of the HTML by using & but if it’s part of a javascript, it will take the code literally. For example, let’s say you have a javascript function that sends you to a URL when you click a button.

function clickMe() {
  window.location = 'http://www.google.com/search?q=javascript+ampersand+xhtml&client=firefox-a';

If you are concerned about being XHTML compliant, you will get an “unknown entity section” error. You can get some more info of the error here http://htmlhelp.com/tools/validator/problems.html. You cannot use “&” in the URL of that javascript function. You can use & (HTML) or & (ASCII). It will solve your error but depending on the browser/version, it will send the code to the URL and will result in an error – especially if your code is dependent on the querystring. To fix this you can use CDATA.


window.location = 'http://www.google.com/search?q=javascript+ampersand+xhtml&client=firefox-a';


The /**/ ignores the lines of code but because your document is XML formatted, CDATA parse the line in between properly (http://www.w3schools.com/xml/xml_cdata.asp). I got answer fromhttp://www.liferay.com/community/forums/-/message_boards/message/2657431#_19_message_2873280.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *