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

Displaying a progress dialog until new activity loads

java android progressdialog

I have a progress dialog I am trying to show when a user clicks a button to launch a new activity. The spinner should be displayed on the current page until the other activity appears. ( The activi...

Check if SecTrustedApplicationRef is a trusted app for a SecKeychainItemRef

objective-c cocoa keychain

I'm trying to go through the keychain and get a list of the Internet Password keychain items that my application has full access to (e.g. won't be prompted). How can i determine that from a

Detect chinese character in a string VB.NET

vb.net split cjk

Is there a way to detect a Chinese character in a string which is build like this: