Telerik blogs

The current article is taken from https://developer.mozilla.org/

In some scenarios it is useful to encode and decode the URI. For example:

To avoid unexpected requests to the server, you should call encodeURIComponent on any user-entered parameters that will be passed as part of a URI. For example, a user could type "Thyme &time=again" for a variable comment. Not using encodeURIComponent on this variable will give comment=Thyme%20&time=again. Note that the ampersand and the equal sign mark a new key and value pair. So instead of having a POST comment key equal to "Thyme &time=again", you have two POST keys, one equal to "Thyme " and another (time) equal to again.

encodeURIComponent

Core Function:

Encodes a Uniform Resource Identifier (URI) component by replacing each instance of certain characters by one, two, or three escape sequences representing the UTF-8 encoding of the character.

Syntax

var encoded = encodeURIComponent(str);

Parameters

 

str - A component of a URI.

 

Description

encodeURIComponent escapes all characters except the following:

alphabetic, decimal digits, - _ . ! ~ * ' ( )

Example

If we encode the URL of this blog:

<script type="text/javascript"> 
  document.write(encodeURIComponent("http://blogs.telerik.com/SupportDept/Posts.aspx")); 
</script>

we will get the following result:

http%3A%2F%2Fblogs.telerik.com%2FSupportDept%2FPosts.aspx

 

decodeURIComponent

Description

Replaces each escape sequence in the encoded URI component with the character that it represents.

Core Function

Decodes a Uniform Resource Identifier (URI) component previously created by encodeURIComponent or by a similar routine.

Syntax

decodeURIComponent(encodedURI)

Parameters
encodedURI - An encoded component of a Uniform Resource Identifier.

Example

We can decode the previously encoded URL to get its original value:

<script type="text/javascript"> 
  var url = encodeURIComponent("http://blogs.telerik.com/SupportDept/Posts.aspx"); 
  document.write(url); 
  document.write("<br />"); 
  document.write(decodeURIComponent(url)); 
</script>

About the Author

Vesselin Vasilev

is an MCTS. He moved to Australia to help Aussie and Kiwi developers build the most awesome web sites in the world. You can find him on twitter @vvassilev or LinkedIn.

Comments

Comments are disabled in preview mode.