When encoding a query string to be sent to a web server - when do you use escape()
and when do you use encodeURI()
or encodeURIComponent()
:
Use escape:
escape("% +&=");
OR
use encodeURI() / encodeURIComponent()
encodeURI("http://www.google.com?var1=value1&var2=value2");
encodeURIComponent("var1=value1&var2=value2");
Small comparison table Java vs. JavaScript vs. PHP.
escape()
Don't use it!
escape()
is defined in section B.2.1.2 escape and the introduction text of Annex B says:Behaviour:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/escape
Special characters are encoded with the exception of: @*_+-./
The hexadecimal form for characters, whose code unit value is 0xFF or less, is a two-digit escape sequence:
%xx
.For characters with a greater code unit, the four-digit format
%uxxxx
is used. This is not allowed within a query string (as defined in RFC3986):A percent sign is only allowed if it is directly followed by two hexdigits, percent followed by
u
is not allowed.encodeURI()
Use encodeURI when you want a working URL. Make this call:
to get:
Don't call encodeURIComponent since it would destroy the URL and return
encodeURIComponent()
Use encodeURIComponent when you want to encode the value of a URL parameter.
Then you may create the URL you need:
And you will get this complete URL:
http://example.net/?param1=http%3A%2F%2Fexample.org%2F%Ffa%3D12%26b%3D55¶m2=99
Note that encodeURIComponent does not escape the
'
character. A common bug is to use it to create html attributes such ashref='MyUrl'
, which could suffer an injection bug. If you are constructing html from strings, either use"
instead of'
for attribute quotes, or add an extra layer of encoding ('
can be encoded as %27).For more information on this type of encoding you can check: http://en.wikipedia.org/wiki/Percent-encoding
I found this article enlightening : Javascript Madness: Query String Parsing
I found it when I was trying to undersand why decodeURIComponent was not decoding '+' correctly. Here is an extract:
I have this function...
encodeURI() - the escape() function is for javascript escaping, not HTTP.
Also remember that they all encode different sets of characters, and select the one you need appropriately. encodeURI() encodes fewer characters than encodeURIComponent(), which encodes fewer (and also different, to dannyp's point) characters than escape().