查看文章
 
JavaScript编码函数之比较
2009-02-06 18:16

1、escape() (ECMAScript v3标准中已经不再使用该函数,建议用encodeURI()和encodeURIComponent()函数替代)
     escape函数对传入的string类型的参数进行编码后返回一个新的字符串。Escape方法会将传入参数中所有的非(ASCII字母、数字以及标点符号@ * _ + - . /)字符替换为%xx或%uxxxx的编码形式,unicode字符\u0000到\u00ff被表示成%xx,其他的unicode字符被表示成%uxxxx,其中x代表一个16进制数。逆函数为unescape(),解码被escape()编码过的字符串。
Example:
escape("http://www.163.com/a?name=hello world,早上好!");
// Returns "http%3A//www.163.com/a%3Fname%3Dhello%20world%2C%u65E9%u4E0A%u597D%21"


2、encodeURI()
     encodeURI函数返回一个经过编码的URI。encodeURI函数会将传入参数先转换为UTF-8的编码,再将参数中所有的非(ASCII字母、数字、标点符号- _ . ! ~ * ' ( )以及在URI中有特殊意义的符号; / ? : @ & = + $ , #)字符替换为一个、两个或三个%xx的编码形式,其中ASCII字符被替换为%xx,\u0080到\u07ff被替换为%xx%xx,其他的16位的uniode字符被替换为%xx%xx%xx。逆函数为decodeURI(),解码被encodeURI()编码过的字符串。
Example:
encodeURI("http://www.163.com/a?name=hello world,早上好!");
// Returns "http://www.163.com/a?name=hello%20world,%E6%97%A9%E4%B8%8A%E5%A5%BD!"


3、encodeURIComponent()
encodeURIComponent函数和encodeURI函数的编码方式相同,但encodeURIComponent函数会对在URI中有特殊意义的符号(; / ? : @ & = + $ , #)进行编码,这是它与encodeURI函数的不同点。其逆函数为decodeURIComponent(),解码被encodeURIComponent()编码过的字符串。
Example:
encodeURIComponent("http://www.163.com/a?name=hello world,早上好!");
// Returns "http%3A%2F%2Fwww.163.com%2Fa%3Fname%3Dhello%20world%2C%E6%97%A9%E4%B8%8A%E5%A5%BD!"  

       当你需要编码一整个URI的时候,你可以使用encodeURI函数,因为URI中的合法字符都不会被编码转换;但是如果你想编码的URI中的某部分(如请求参数)含有URI中有特殊意义的符号,你就应该使用encodeURIComponent函数对这个部分单独进行编码。

---------------------------end----------------------  

       由于项目需求,需要在CGI中解码经encodeURIComponent()编码后的字符串,python中没有现成函数,自写了一山寨encodeURIComponent():

   def decodeURIComponent(str):

         def replace(match):

               return chr(int(match.group(2),16))

         return re.sub(r"(%)([0-9A-Za-z]{2})", replace, str).decode('utf-8').encode('gb2312')

   #这里:GB2312是被encodeURIComponent()编码前的原字符串的编码。

        


类别:工作日志||添加到搜藏 |分享到i贴吧|浏览(685)|评论 (0)
 
最近读者:
 
网友评论:
发表评论:
姓 名:
网址或邮箱: (选填)
内 容:
     

   
帮助中心 | 空间客服 | 投诉中心 | 空间协议
©2012 Baidu