JaPerk14
JaPerk14

Reputation: 1664

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.

Upvotes: 1

Views: 865

Answers (2)

M. Cypher
M. Cypher

Reputation: 7066

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.

Upvotes: 5

Taylor
Taylor

Reputation: 393

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

Upvotes: 6

Related Questions