js中三种URI编码方式比较

发布时间 2023-12-29 13:56:04作者: LiangSenCheng小森森

一、实例比较

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

var url = "https://www.cnblogs.com/?username='小森森'&password='666666'";

escape 与 unescape

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

结果:

https%3A//www.cnblogs.com/%3Fusername%3D%27%u5C0F%u68EE%u68EE%27%26password%3D%27666666%27

encodeURIComponent 与 decodeURIComponent (推荐)

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

结果:

https%3A%2F%2Fwww.cnblogs.com%2F%3Fusername%3D'%E5%B0%8F%E6%A3%AE%E6%A3%AE'%26password%3D'666666'

encodeURI 与 decodeURI

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

结果:

https://www.cnblogs.com/?username='%E5%B0%8F%E6%A3%AE%E6%A3%AE'&password='666666'

二、区别分析

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

escape 与 unescape

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

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

encodeURIComponent 与 decodeURIComponent

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

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

encodeURI 与 decodeURI

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

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

三、结论

推荐使用encodeURIComponent

四、原文链接

js中三种URI编码方式比较