Last Updated: September 02, 2017
·
40.07K
· johnnyrodgers

encodeURI() vs. encodeURIComponent()

I used to think that these two JavaScript functions did the same thing: encode special characters in a URL string so that it could be safely used to make an HTTP request.

Turns out I was missing the point: encodeURI() will encode a URL string but not the parameters or hash. So:

encodeURI("http://www.google.com/results with spaces#some-anchor")

returns:

http://www.google.com/results%20with%20spaces#some-anchor

While encodeURIComponent() on the same string will return:

http%3A%2F%2Fwww.google.com%2Fresults%20with%20spaces%23some-anchor

What we actually want for a well formed URL is to call encodeURI() on the base URL:

encodeURI("http://www.google.com/results with spaces")
http://www.google.com/results%20with%20spaces

And encodeURIComponent() on the hash:

encodeURIComponent("#some-anchor")
%23some-anchor

I understood my mistake thanks to this excellent SO answer: http://stackoverflow.com/a/3608791/363813.

http://www.w3schools.com/jsref/jsref_encodeuri.asp points out that encodeURI() encodes special characters, except: , / ? : @ & = + $ # (Use encodeURIComponent() to encode these characters).