encodeURIComponent and decodeURIComponent

What do these global JavaScript methods do? Well they are the replacements for the now long obsolete escape and unescape functions. Let's see exactly how they work by using them to convert some text in the following text box.

Most of the characters that you typed except for letters and numbers were converted to special codes consisting of a percentage character followed by the a hexadecimal equivalent of the unicode value of the character that they replaced (escape and unescape could only handle the 127 ASCII characters - which is why those function have been replaced). If you click the decode button it will convert the converted text back into what you originally typed. (Pressing the encode button again will convert all of the % symbols into %25 making the text longer but will not affect any of the other characters in the escaped text.)

Why would we use this? Well if we are going to use a character string for something where certain characters are assigned a special meaning (for example <, >, and & in html - we can avoid having these codes confused for html markup by escaping the text that contains them and then using the decodeURIComponent function to restore them to normal later). Encoding the text is particularly useful for converting parameters to be passed in the querystring on the end of a URL or when we want to store the parameters in cookies as there are characters that have special meanings in these and we don't want to get our parameters mixed up with those special characters.

One area where escaping the text is not useful at all is in attempting to apply some form of encryption to your page source. Where using encodeURIComponent only converts non alphanumerics, decodeURIComponent will convert all of the supplied information even where the codes match to alphanumerics that would not have been escaped in the first place. Suppose that you saw decodeURIComponent('%65%6d%61%69%6c') in the source code of a page (in an actual page the code might be thousands of characters long but 15 will do for this example). Is that code encrypted so that visitors to the site cannot read your source code. Not really. Just highlight the code and copy it into the above text box and press the decode button and it will be converted instantly to clear text.

 

This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow
Donate