I am encoding a string that will be passed in a URL (via GET). But if I use escape
, encodeURI
or encodeURIComponent
, &
will be replaced with %26amp%3B
, but I want it to be replaced with %26
. What am I doing wrong?
This question is related to
javascript
urlencode
If you did literally this:
encodeURIComponent('&')
Then the result is %26
, you can test it here. Make sure the string you are encoding is just &
and not &
to begin with...otherwise it is encoding correctly, which is likely the case. If you need a different result for some reason, you can do a .replace(/&/g,'&')
before the encoding.
There is HTML and URI encodings. &
is &
encoded in HTML while %26
is &
in URI encoding.
So before URI encoding your string you might want to HTML decode and then URI encode it :)
var div = document.createElement('div');
div.innerHTML = '&AndOtherHTMLEncodedStuff';
var htmlDecoded = div.firstChild.nodeValue;
var urlEncoded = encodeURIComponent(htmlDecoded);
result %26AndOtherHTMLEncodedStuff
Hope this saves you some time
Source: Stackoverflow.com