Escaping ampersand in URL

tomermes picture tomermes · May 18, 2013 · Viewed 316.9k times · Source

I am trying to send a GET message that contains strings with ampersands and can't figure how to escape the ampersand in the URL.

Example:

http://www.example.com?candy_name=M&M
result => candy_name = M

I also tried:

http://www.example.com?candy_name=M\&M
result => candy_name = M\\

I am using URLs manually, so I just need the correct characters.

I can't use any libraries. How can it be done?

Answer

Blender picture Blender · May 18, 2013

They need to be percent-encoded:

> encodeURIComponent('&')
"%26"

So in your case, the URL would look like:

http://www.mysite.com?candy_name=M%26M