2010-10-29

Javascript Encode URL, Escape String

Perm url with updates: http://xahlee.org/js/js_encode_url.html

Javascript Encode URL, Escape String

Xah Recommends:
Kindle
Amazon Kindle. Read books under the sun. Review

Xah Lee, 2010-10-29

This pages shows you how to use javascript to do percent encoding for URI.

There are these js functions to do encoding and decoding.

  • encodeURI, decodeURI
  • encodeURIComponent, decodeURIComponent
  • escape, unescape

encodeURI and encodeURIComponent

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.

For detail, see: Percent-encoding.

The “escape” Function

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

Sample Template; Test Yourself

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>");
Was this page useful? If so, please do donate $3, thank you donors!