JS中三种URI编码方式对比分析

 更新时间:2024年01月03日 09:34:11   作者:LiangSenCheng小森森  
这篇文章主要介绍了JS中三种URI编码方式对比分析,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧

一、实例比较

数据传递常需要编码后传递,接收还需反编译,定义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编码方式比较的文章就介绍到这了,更多相关js URI编码内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

最新评论