Why url encode, or which characters to encode

http://www.w3schools.com/tags/ref_urlencode.asp

Since URLs often contain characters outside the ASCII set, the URL has
to be converted into a valid ASCII format.

But both space, /, % are part of the ASCII character set, so why encode them in the first place? What characters should be encoded?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

The characters in a URL should be encoded because some characters have a special meaning according to the URL specification, some characters are not allowed and some characters are not representable in all character sets.

See this intro for a little more guidance.

Regarding the examples of characters that you give ‘/’ is reserved for use as a component separator in URLs and ‘%’ is used as an escape character.

Method 2

As noted, spaces are not valid in URLs. Most browsers orlencode them automatically. However…

The page you linked to has an example using the word “Günter” in the “Try me” section. If the word “Günter” were sent as a querystring parameter, it wouldn’t work. as the “ü” is not in the standard ASCII character set.

It’s meant to be used when there are potentially non-ASCII characters. An example might be when using data from a database to create a hyperlink. Suppose the code creates a link to a user profile page. Unencoded, mine would be:

<a href="profile/?username=David Stratton" rel="nofollow noreferrer noopener">Your profile</a>

while Günter’s would be

<a href="profile/?username=Günter" rel="nofollow noreferrer noopener">Your profile</a>

Mine, most browsers could handle. Günter’s, probably not.

Encoded, these would become

<a href="profile/?username=David%20Stratton" rel="nofollow noreferrer noopener">Your profile</a>

and

<a href="profile/?username=G%FCnter" rel="nofollow noreferrer noopener">Your profile</a>

which are valid URLs.

(Please forgive the fact that most well-designed systems wouldn’t pass a username in a parameter like that. This was just a sample to clarify the concept.)

Method 3

Here you go:

When are you supposed to use escape instead of encodeURI / encodeURIComponent?

This is the best explanation I found and was helpful to me.

Method 4

Certain characters, such as spaces, need to be escaped to ensure valid urls. Once place where this is sure to come up a lot is when generating GET parameters.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x