escape() encodeURI() encodeURIComponent()
编码 解码
摘要:
- escape()不能直接用于URL编码,它的真正作用是返回一个字符的Unicode编码值。比如”春节”的返回结果是%u6625%u8282,,escape()不对”+”编码 主要用于汉字编码,现在已经不提倡使用。
- encodeURI()是Javascript中真正用来对URL编码的函数。 编码整个url地址,但对特殊含义的符号”; / ? : @ & = + $ , #”,也不进行编码。对应的解码函数是:decodeURI()。
- encodeURIComponent() 能编码”; / ? : @ & = + $ , #”这些特殊字符。对应的解码函数是decodeURIComponent()。
假如要传递带&符号的网址,所以用encodeURIComponent()
详总:
http://www.haorooms.com/post/js_escape_encodeURIComponent
解码例子
针对escape、encodeURI、encodeURIComponent三种编码方式,根据其编码特征来处理
1、escape,特征最为明显,对于值小与255的字符编码格式为%[a-zA-Z0-9]{2},对值大于255的字符编码格式为%u[a-zA-Z0-9]{4},
escape不进行编码的字符有69个: ,+,-,.,/,@,_,0-9,a-z,A-Z
2、encodeURI,编码格式为%[a-zA-Z0-9]{2},
encodeURI不进行编码的字符有82个:!,#,$,&,’,(,),,+,,,-,.,/,:,;,=,?,@,,~,0-9,a-z,A-Z
3、encodeURIComponent三种编码方式,编码格式为%[a-zA-Z0-9]{2},
encodeURIComponent不进行编码的字符有71个:!, ‘,(,),*,-,.,,~,0-9,a-z,A-Z
提取三种编码方式不同的部分:
-当字符的值小于255时,三种编码方式结果相同,可以任意使用一种解码方式
-当字符的值大于255时,escape编码的结果与另外两者不同,可根据其编码特征来处理,即当编码格式为%u[a-zA-Z0-9]{4}时,使用unescape解码,
-当编码格式为%[a-zA-Z0-9]{2}时,因为encodeURIComponent不进行编码的字符少于encodeURI,
则可判断decodeURIComponent可以同时针对encodeURI和因为encodeURIComponent两种编码方式进行解码
记录解码结果,如果解码后与原字符串相同,则结束递归