首页 > 代码库 > uri编解码

uri编解码

 

相关函数如下:(都是全局函数)

encodeURI(URIString):将文本字符串编码为有效的统一资源标示符URIdecodeURI(URIString)encodeURIComponent(s):编码URI的一部分或者是其他待编码的字符串decodeURIComponent(s)

 


 

encodeURI编码规则:

  1、对于encodeURI(),ASCII字母、数字、"- _  .  !  ~ * ‘ ()"等标点不会编码;

  2、由于encodeURI用于编码URI,因而在uri中具有具有特殊意义的ASCII标点也不会编码,例如: ; / ? : @ = + $ , #

  3、uri中其他字符将被转换为对应的utf-8编码;

    1、0001—007E(ASCII字符)编码为%xx

    2、\u0080—\u07ff之间的unicode字符,用%xx%xx编码

    3、\u0800—\uffff 之间的unicode字符均被编码为%xx%xx%xx

    4、使用该方法编码时应确保URI中不包含? # 等字符,否则应该使用encodeURIComponent对uri每部分单独编码

 

encodeURIComponent:

  1、ASCII字母、数字、"- _  .  !  ~ * ‘ ()"等标点不会编码;

  2、/ ? : @ = + $ , #等用来分隔uri的会被编码

 

注意:

  1、ECMAScript3前可以使用escape()和unescape执行类似encodeURI的编码,现在已经弃用

  2、encodeURIComponent设参数是URI的一部分,因而用于分割URI不同部分的字符会被编码

  3、URI中包含/ ? : @ = + $ 等时应该用encodeURIComponent对uri每部分单独编码

  4、使用encodeURIComponent编码后,可以使用decodeURI解码也可以使用decodeURIcomponent解码

 


  

eg:

 

var uriEncode = encodeURI("http://www.cnblogs.com/wishyouhappy");var uriDeocde = decodeURI(uriEncode);console.log("uriEncode: " + uriEncode); //uriEncode: http://www.cnblogs.com/wishyouhappy console.log("uriDeocde: " + uriDeocde); //uriDeocde: http://www.cnblogs.com/wishyouhappy //,/?:@&=+$#未被编码var uriEncode = encodeURI(",/?:@&=+$#");var uriDeocde = decodeURI(uriEncode);console.log("uriEncode: " + uriEncode); //,/?:@&=+$# console.log("uriDeocde: " + uriDeocde); //,/?:@&=+$# //此例中空格编码为%20, 汉字编码为%xx%xx%xxvar uriEncode = encodeURI("http://www.cnblogs.com?name = ‘流光‘");var uriDeocde = decodeURI(uriEncode);console.log("uriEncode: " + uriEncode); //http://www.cnblogs.com?name%20=%20‘%E6%B5%81%E5%85%89‘ console.log("uriDeocde: " + uriDeocde); // http://www.cnblogs.com?name = ‘流光‘ //使用encodeURIComponent编码后使用uriDeicode和uriDecodeComponent都可以解码var uriEncode = encodeURIComponent("Are you happy?");var uriDeocde = decodeURI(uriEncode);var uriDecodeComponent = decodeURIComponent(uriEncode);console.log("uriEncode: " + uriEncode); // Are%20you%20happy%EF%BC%9F console.log("uriDeocde: " + uriDeocde); //Are you happy?console.log("uriDecodeComponent: " + uriDecodeComponent); //Are you happy?var uriEncode = encodeURIComponent(",/?:@&=+$#");var uriDecodeComponent = decodeURIComponent(uriEncode);console.log("uriEncode: " + uriEncode); //%2C%2F%3F%3A%40%26%3D%2B%24%23 console.log("uriDecodeComponent: " + uriDecodeComponent); //,/?:@&=+$#