Take the 2-minute tour ×

I'm currently learning JavaScript, and I don't understand why it is important to encode URLs.

>>> var url = 'http://www.packtpub.com/scr ipt.php?q=this and that';
>>> encodeURI(url);


For instance, in this example what purpose would it serve to change the first URL to the latter one.

share|improve this question
Because otherwise it's impossible to tell, for example, whether ? is part of the URL string or to indicate the beginning of GET parameters. –  Jack Maney Sep 8 '12 at 23:53
add comment

2 Answers

up vote 4 down vote accepted

Only a limited number of characters are allowed in URLs, according to the RFC 3986 standard. If you have a space in a URL, for example, this will make the URL invalid unless you encode it.

Often, browsers can deal with URLs that are not properly encoded by doing the encoding themselves, but that's not something you should rely on as a web developer.

URL encoding is also critical when using URLs as parameters of another URL. In this case the reserved characters of the URL need to be encoded, not just the non-permitted characters. For this, however, you don't use encodeURI, but encodeURIComponent.

share|improve this answer
add comment

It depends on what you're going to be doing with that URL.

When you just use a document.location = url, you don't want it encoded.

If you plan on passing that URL as a variable, then yes you want it encoded or it will confuse the browser. For instance:


See how that could be confusing to the browser?

By the way, never use a space in a url or php file. i've always found that to cause unnecessary stress. :)

share|improve this answer
add comment

Your Answer


