escape 方法

对 String 对象编码以便它们能在所有计算机上可读,

escape(charString)

必选项 charstring 参数是要编码的任意 String 对象或文字。

说明

escape 方法返回一个包含了 charstring 内容的字符串值( Unicode 格式)。所有空格、标点、重音符号以及其他非 ASCII 字符都用 %xx 编码代替,其中 xx 等于表示该字符的十六进制数。例如,空格返回的是 “%20” 。

字符值大于 255 的以 %uxxxx 格式存储。

unescape 方法

解码用 escape 方法进行了编码的 String 对象。

unescape(charstring)

必选项 charstring 参数是要解码的 String 对象。

说明

unescape 方法返回一个包含 charstring 内容的字符串值。所有以 %xx 十六进制形式编码的字符都用 ASCII 字符集中等价的字符代替。

以 %uxxxx 格式(Unicode 字符)编码的字符用十六进制编码 xxxx 的 Unicode 字符代替.

——————————————————————————————————————————-

这两个函数的功能是用来将字符进行编码我反编码(解码),其主要用途在使用cookie时经常用到这两个函数,因为在要对cookie进行写入时, 那些特殊字符(符号和汉字)需要进行编码才能写入,所以在读取时就需要用到unescape函数进行解码再显示,下面是一点例子:

//—————————————————————————-

// Set a cookie given a name, value and expiration date.

//—————————————————————————-

function setCookie (name, value,len) {

var date = new Date ();

len = len || 86400 * 1000 * 2;

date.setTime (date.getTime() + len * 1000);

document.cookie = name + “=” + escape(value) + “; expires=” + date.toGMTString() +??? “; path=/“;

if(document.cookie.length > 1024){

deleteCookie(name);

}

}

//—————————————————————————-

// Returns the value of the named cookie.

//—————————————————————————-

function getCookie(name) {

var search;

search = name + “=”;

offset = document.cookie.indexOf(search) ;

if (offset != -1) {

offset += search.length;

end = document.cookie.indexOf(“;”, offset);

if (end == -1)

end = document.cookie.length;

return unescape(document.cookie.substring(offset, end));

}

else

return “”;

}