Javascript: escape() vs. encodeURI() vs. encodeURIComponent()

Are you great JavaScript programmer? Yes? Do you know the difference in mentioned methods and when to use which? No? Oh I see…you take a peek at w3schools.com when you need it! Ok, me too!

I’m searching for this too many times! So I guess If I write about it it’ll stick for a few days longer in my head…will see about that.

So let’s go..when it’s appropriate times to use which?

The escape() method does not encode the + character which is interpreted as a space on the server-side as well as generated by forms with spaces in their fields. Due to this shortcoming and the fact that this function fails to handle non-ASCII characters correctly, you should avoid use of escape() whenever possible. The best alternative is usually encodeURIComponent().

This function encodes special characters, except: * @ - _ + . /

Use of the encodeURI() method is a bit more specialized than escape() in that it encodes for URIs as opposed to the querystring (which is only part of a URL). Use this method when you need to encode a string to be used for any resource that uses URIs and needs certain characters to remain un-encoded. Note that this method does not encode the ' character, as it is a valid character within URIs.

This function encodes special characters, except: , / ? : @ & = + $ #

Lastly, the encodeURIComponent() method should be used in most cases when encoding a single component of a URI. This method will encode certain chars that would normally be recognized as special chars for URIs so that many components may be included. Note that this method does not encode the ' character, as it is a valid character within URIs.

This function encodes special characters. In addition, it ALSO encodes the following characters: , / ? : @ & = + $ #

That’s it, now you know and I remember!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s