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.

/*<![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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s