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?
They need to be percent-encoded:
So in your case, the URL would look like:
You can rather pass your arguments using this encodeURIComponent function so you don't have to worry about passing any special characters.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent
This does not only apply to the ampersand in URLs, but to all reserved characters. Some of which include:
The idea is the same as encoding an
&
in an HTML document, but the context has changed to be within the URI, in addition to being within the HTML document. So, the percent-encoding prevents issues with parsing inside of both contexts.The place where this comes in handy a lot is when you need to put a URL inside of another URL. For example, if you want to post a status on Twitter:
There's lots of reserved characters in my Tweet, namely
?'():/
, so I encoded the whole value of thestatus
URL parameter. This also is helpful when usingmailto:
links that have a message body or subject, because you need to encode thebody
andsubject
parameters to keep line breaks, ampersands, etc. intact.http://en.wikipedia.org/wiki/Percent-encoding#Percent-encoding_reserved_characters
If you can't use any libraries to encode the value, http://www.urlencoder.org/ or http://www.urlencode-urldecode.com/ or ...
Just enter your value "M&M", not the full URL ;-)
Try using
http://www.example.org?candy_name=M%26M
.See also this reference and some more information on Wikipedia.
You can use the % character to 'escape' characters that aren't allowed in URLs. See [RFC 1738].
A table of ASCII values on http://www.asciitable.com/.
You can see
&
is 26 in hexadecimal - so you need M%26M.