views:

7850

answers:

5

When encoding a query string to be sent to a web server - what is the best practice to use from javascript:

Use escape:

escape("% +&=");

OR

use encodeURI() / encodeURIComponent()

encodeURI("http://www.google.com?var1=value1&var2=value2");

encodeURIComponent("var1=value1&var2=value2");
+11  A: 

encodeURI() - the escape() function is for javascript escaping, not HTTP.

Daniel Papasian
If i have a url like this: `var url = "http://kuler-api.adobe.com/rss/get.cfm?startIndex=0`... then I have to use `escape(url)`. `encodeURI(url)` doesn't work with parameters like that it seems.
viatropos
+2  A: 

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().

Pseudo Masochist
+5  A: 

As Danny Goodman points out in Javascript, The Definitive Guide, escape() was ECMAScript v1 and deprecated in ECMAScript v3. General advice seems to be to avoid using it.

+10  A: 

This has been explained quite well at the foll link:

http://xkr.us/articles/javascript/encode-compare/

+5  A: 

escape()

Don't use it.

encodeURI()

Use encodeURI when you want a working URL. Make this call:

encodeURI("http://www.google.com/a file with spaces.html")

to get:

http://www.google.com/a%20file%20with%20spaces.html 

Don't call encodeURIComponent since it would destroy the URL and return

http%3A%2F%2Fwww.google.com%2Fa%20file%20with%20spaces.html

encodeURIComponent()

Use encodeURIComponent when you want to encode a URL parameter.

param1 = encodeURIComponent("http://xyz.com/a=12&b=55")

Then you may create the URL you need:

url = "http://domain.com/param1=" + param1 + "&param2=99";

And you will get this complete URL:

http://domain.com/param1=http%3A%2F%2Fxyz.com%2Fa%3D12%26b%3D55&param2=99
Arne Evertsson