Why is character encoding important for URLs?

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);

"http://www.packtpub.com/scr%20ipt.php?q=this%20and%20that"

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

Answers


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.


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:

http://www.someurl.com?myFavwebsite=http://www.stackoverflow.com?someParam=test.

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


Need Your Help

XML Repository; to Save() or not to Save()

c# .net xml oop repository

What would be a better approach for an xml-based repository:

Is the new GIL in Python 3.2 sufficient to make the switch?

python gil

I was reading this page on the new GIL found/to be found in Python 3.2 and I was wondering if it is the "killer feature" that will trigger a transition from Python 2.x to 3.x.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.