js中三种URI编码方式比较

js中三种URI编码方式比较

1. 实例

数据传递常需要编码后传递,接收还需反编译,定义url:

var url = "http://www.csxiaoyao.com?username='CS逍遥剑仙'&password='19931128'";

1.1【escape & unescape】

console.log(escape(url));// 编码
console.log(unescape(escape(url)));// 解码

结果

http%3A//www.csxiaoyao.com%3Fusername%3D%27CS%u900D%u9065%u5251%u4ED9%27%26password%3D%2719931128%27

1.2【encodeURIComponent & decodeURIComponent】【推荐】

console.log(encodeURIComponent(url));// 编码
console.log(decodeURIComponent(encodeURIComponent(url)));// 解码

结果

http%3A%2F%2Fwww.csxiaoyao.com%3Fusername%3D'CS%E9%80%8D%E9%81%A5%E5%89%91%E4%BB%99'%26password%3D'19931128'

1.3【encodeURI & decodeURI】

console.log(encodeURI(url));// 编码
console.log(decodeURI(encodeURI(url)));// 解码

结果

http://www.csxiaoyao.com?username='CS%E9%80%8D%E9%81%A5%E5%89%91%E4%BB%99'&password='19931128'

2. 区别分析

三种方法都不会对 ASCII 字母、数字和规定的特殊 ASCII 标点符号进行编码,其余都替换为十六进制转义序列
【escape & unescape】

escape不编码字符有69个:*,+,-,.,/,@,_,0-9a-z,A-Z  

对字符串全部进行转义编码,ECMAScript v3 反对使用该方法,对URL编码勿使用此方法
【encodeURIComponent & decodeURIComponent】

 encodeURIComponent不编码字符有71个:!, ',(,),*,-,.,_,~,0-9a-z,A-Z  

传递参数时需使用encodeURIComponent,组合的url才不会被#等特殊字符截断
【encodeURI & decodeURI】

encodeURI不编码字符有82个:!,#,$,&,',(,),*,+,,,-,.,/,:,;,=,?,@,_,~,0-9,a-z,A-Z

进行url跳转时可以整体使用encodeURI,如果URI中含分隔符如 ? 和 #,应使用encodeURIComponent

3. 结论

推荐使用encodeURIComponent

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值