Javascript Encode URL, Escape String

Perm url with updates:

Javascript Encode URL, Escape String

Xah Recommends:
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:–Gallai_theorem

The dash above is a en-dash, unicode 8211 (U+2013).




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.


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" "">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>test page</title>

<script type="text/javascript" src="mytest.js"></script>


Here's js template:

var uri="–Gallai_theorem";


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");

Was this page useful? If so, please do donate $3, thank you donors!

Popular posts from this blog

11 Years of Writing About Emacs

does md5 creates more randomness?

Google Code shutting down, future of ErgoEmacs