Xah Lee, 2010-10-29
This pages shows you how to use javascript to do percent encoding for URI. If you are not familiar with js, see: Javascript Basics.
There are these js functions to do encoding and decoding.
encodeURI and encodeURIComponent are used for encode a URI. The difference is that encodeURIComponent will also encode the “http://” part. Here's a sample uri:
http://en.wikipedia.org/wiki/Sylvester–Gallai_theorem
The dash above is a en-dash, unicode 8211 (U+2013).
Result:
encodeURI: http://en.wikipedia.org/wiki/Sylvester%E2%80%93Gallai_theorem encodeURIComponent: http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FSylvester%E2%80%93Gallai_theorem
The %E2%80%93 are hexadecimals E2 80 93,
and is the byte sequence of the en dash char by utf-8 encoding.
The “escape” is similar to encodeURI, but it is used to encode any string not just URI, and it only encode certain characters.
Here's its result.
http%3A//en.wikipedia.org/wiki/Sylvester%u2013Gallai_theorem
You can test these functions on strings that contain any unicode char or Chinese. e.g. ° © ® ™ § ¶ † ‡ ※ ◀▶▲▼ ♤♧♡♢ 林花謝了春紅. Here's a html template:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <title>test page</title> </head> <body> <script type="text/javascript" src="mytest.js"></script> </body> </html>
Here's js template:
var uri="http://en.wikipedia.org/wiki/Sylvester–Gallai_theorem"; document.write("<pre>"); document.write( "encodeURI:\n"); document.write( encodeURI(uri) + "\n\n"); document.write( "encodeURIComponent:\n"); document.write( encodeURIComponent(uri) + "\n\n"); document.write( "escape:\n"); document.write( escape(uri) + "\n\n"); document.write("</pre>");