Monday 5 March 2012

What is the difference between decodeURIComponent and decodeURI?

Sometimes, we post the request (search for instance) with the value of parameter ("keyword" for instance) passing on the URI, like below:

var uri="http://www.myweb.com/search.asp?keyword=lập trình C++&includecomment=true";
If keyword parameter contains the special characters like , / ? : @ & = + $ #..., the URI will be parsed incorrectly. So we have to encode the parameter.

Examples:
alert(encodeURI('lập trình C++')); ==> Return: l%E1%BA%ADp%20tr%C3%ACnh%20C++

alert(encodeURIComponent('lập trình C++')); ==> Return:l%E1%BA%ADp%20tr%C3%ACnh%20C%2B%2B

alert(encodeURI('http://www.myweb.com/search.asp?keyword=lập trình C++&includecomment=true')); ==> Return: http://www.myweb.com/search.asp?keyword=l%E1%BA%ADp%20tr%C3%ACnh%20C++&includecomment=true

alert(encodeURIComponent('http://www.myweb.com/search.asp?keyword=lập trình C++&includecomment=true')); ==> Return: http%3A%2F%2Fwww.myweb.com%2Fsearch.asp%3Fkeyword%3Dl%E1%BA%ADp%20tr%C3%ACnh%20C%2B%2B%26includecomment%3Dtrue

From MSDN JScript Reference:
The encodeURI method returns an encoded URI. If you pass the result to decodeURI, the original string is returned. The encodeURI method does not encode the following characters: ":", "/", ";", and "?". Use encodeURIComponent to encode these characters.

EncodeURI
, sometimes called fixBrokenURI or produces a "safe" URI by encoding invalid characters such as spaces and some other (e.g. nonprintable), and turns it into a real URI. It has a valid use in fixing up invalid URIs from user input, and it can also be used to turn an IRI (URI with bare Unicode characters in) into a plain URI (using %-escaped UTF-8 to encode the non-ASCII).

EncodeURIComponent
encodes the colon and slash and plus characters, and is meant to be used in query strings. The encoding of + and ? and & is of particular importance here, as these are special chars in query strings.

Now you know the real difference between EncodeURI() and EncodeURIComponent().
Converserly, DecodeURI() and DecodeURIComponent() is provided to be an inverse of EncodeURI and EncodeURIComponent.

And here the real Web example:

<input type="text" name="keyword" id="keyword" value="<%=Server.HtmlEncode(Request.QueryString["keyword"]) %>" onkeypress="if(event.keyCode==13) SearchPage()" />
document.write(encodeURIComponent(uri));
   <script type="text/javascript">    
    //<![CDATA[
     
      function SearchPage()
      {      
        var searchTerm = encodeURIComponent(document.getElementById('keyword').value); //Return "l%E1%BA%ADp%20tr%C3%ACnh%20C%2B%2B"
        var includecomment = '&comment=true';

        location.href = 'search.aspx?q=' + searchTerm + comment; //Now the query string is safe, isn't it?   Encoded URL = http://www.myweb.com/search.asp?keyword=l%E1%BA%ADp%20tr%C3%ACnh%20C%2B%2B&includecomment=true
      }
      //]]>
    </script>

Happy Coding,

No comments:

Post a Comment