您的位置:首页 > Web前端 > JavaScript

JS编码

2013-12-14 14:26 106 查看

escape()和unescape()函数

escape -- 使用转义序列编码字符串

不符合ECMA标准,不赞成使用.
escape,中文"逃避,逃脱"的意思
引用网址:http://www.dreamdu.com/javascript/escape/

escape函数语法

        escape(str);

 escape函数参数

str -- 需要编码的字符串

escape函数返回值

对str使用了转义序列编码的字符串

escape函数说明

escape是一个全局函数,它将使用十六进制的数字(%xx或%uxxxx)编码字符串。小于等于0xFF的字符将被转义为%xx,大于0xFF的将被转移为%uxxxx。

可以使用unescape函数解码escape函数编码的字符串

escape已被ecma标准抛弃,请使用encodeURI或encodeURIComponent函数代替

示例

var str="梦之都 http://www.dreamdu.com/"; str=escape(str);
document.write(str);
str=unescape(str);
document.write(str);


 结果:

%u68A6%u4E4B%u90FD%20http%3A//www.dreamdu.com/
梦之都 http://www.dreamdu.com/

 

encodeURI()和decodeURI()函数

encodeURI -- 转义某些字符串对URI编码

encode,中文"编码"的意思
引用网址:http://www.dreamdu.com/javascript/encodeURI/

encodeURI函数语法

       encodeURI(str);

encodeURI函数参数

str -- 要编码的字符串(通常为一个URI)

encodeURI函数返回值

str编码后的字符串(原str中的某些字符被十六进制的转义序列替换)

encodeURI函数说明

encodeURI是全局函数。encodeURI的目的是给URI进行编码。ASCII的字母、数字不编码,- _ . ! ~ * ' ( )也不编码,URI中具有特殊意义的字符也不编码; ; / ? : @ & = + $ , # 空格

参数中的其他字符将转换成UTF-8编码方式的字符,并使用十六进制转义序列(%xx)生成替换。其中,ASCII字符使用一个%xx替换,在\u0080与\u07ff之间的编码的字符使用两个%xx替换,其它的16为Unicode字符使用三个%xx替换。

如果想对URI的分隔符? #编码,应该使用encodeURIComponent。

使用decodeURI可以还原encodeURI编码的字符串。

示例

var str="梦之都 http://www.dreamdu.com/"; str=encodeURI(str);
document.write(str);
str=decodeURI(str);
document.write(str);
str=encodeURI(";/?:@&=+$,#-_.!~*'()");
document.write(str);
str=encodeURIComponent(";/?:@&=+$,#-_.!~*'()");
document.write(str);


结果:

%E6%A2%A6%E4%B9%8B%E9%83%BD%20http://www.dreamdu.com/
梦之都 http://www.dreamdu.com/ ;/?:@&=+$,#-_.!~*'()
%3B%2F%3F%3A%40%26%3D%2B%24%2C%23-_.!~*'()

 

encodeURIComponent()和decodeURIComponent()函数

encodeURIComponent -- 转义某些字符串对URI的组件编码

encode,中文"编码"的意思
引用网址:http://www.dreamdu.com/javascript/encodeURIComponent/

encodeURIComponent函数语法

         encodeURIComponent(str);

encodeURIComponent函数参数

str -- 要编码的字符串(通常为一个URI)

encodeURIComponent函数返回值

str编码后的字符串(原str中的某些字符被十六进制的转义序列替换)

encodeURIComponent函数说明

encodeURIComponent是全局函数。encodeURIComponent的目的是给URI进行编码。与encodeURI函数的不同encodeURIComponent会对URI中具有特殊意义的字符也进行编码; ; / ? : @ & = + $ , # 空格,其它的与encodeURI相同。

示例

var str="梦之都 http://www.dreamdu.com/"; str=encodeURIComponent(str);
document.write(str);
str=decodeURIComponent(str);
document.write(str);
str=encodeURI(";/?:@&=+$,#-_.!~*'()");
document.write(str);
str=encodeURIComponent(";/?:@&=+$,#-_.!~*'()");
document.write(str);


 结果:

%E6%A2%A6%E4%B9%8B%E9%83%BD%20http%3A%2F%2Fwww.dreamdu.com%2F
梦之都 http://www.dreamdu.com/
;/?:@&=+$,#-_.!~*'()
%3B%2F%3F%3A%40%26%3D%2B%24%2C%23-_.!~*'()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: