Main Page

URI methods

This code outputs two values:
http://www.wrox.com/illegal%20value.htm#start
http%3A%2F%2Fwww.wrox.com%2Fillegal%20value.htm%23start
As you can see, the first URI was left intact except for the space, which was replaced with
%20
. The second
URI replaced all non-alphanumeric characters with their encoded equivalents, which essentially makes
this URI useless. This is why
encodeURI()
can be used on full URIs, whereas
encodeURIComponent()
can only be used on strings that are appended to the end of an existing URI.
Naturally, there are also two methods to decode URIs that have already been encoded, called
decodeURI()
and
decodeURIComponent()
. As you might expect, these methods do the exact opposite
of their counterparts. The
decodeURI()
method only decodes characters that have been replaced by
using
encodeURI()
. For instance
%20
is replaced with a space, but
%23
is not replaced because it repre-
sents a pound sign (#), which
encodeURI()
does not replace. Likewise,
decodeURIComponent()
decodes all characters encoded by
encodeURIComponent()
, essentially meaning it decodes all special
values. Example:
var sUri = “http%3A%2F%2Fwww.wrox.com%2Fillegal%20value.htm%23start”;
alert(decodeURI(sUri));
alert(decodeURIComponent(sUri));
This code outputs two values:
http%3A%2F%2Fwww.wrox.com%2Fillegal value.htm%23start
http://www.wrox.com/illegal value.htm#start
In this example, the
uri
variable contains a string that is encoded using
encodeURIComponent()
. The
resulting values show what happens when you apply the two decoding methods. The first value is
the output of
decodeURI()
, which replaced only
%20
with a space; the second value is the output of
decodeURIComponent()
, which replaces all the special characters.
The final method is perhaps the most powerful in the entire ECMAScript language, the
eval()
method.
This method works like an entire ECMAScript interpreter and accepts one argument, a string of
ECMAScript (or JavaScript) to execute. For example:
eval(“alert(‘hi’)”);
This line is functionally equivalent to the following:
alert(“hi”);
These URI methods,
encodeURI()
,
encodeURIComponent()
,
decodeURI()
, and
decodeURIComponent()
, replace the BOM methods
escape()
and
unescape()
.
The URI methods are always preferable because they encode all Unicode characters,
whereas the BOM methods encode only ASCII characters correctly. Avoid using
escape()
and
unescape()
.
82
Chapter 3
06_579088 ch03.qxd 3/28/05 11:36 AM Page 82


JavaScript EditorFree JavaScript Editor     Ajax Editor


©

R7