;

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编码方式比较

posted @   LiangSenCheng小森森  阅读(149)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!

文章目录[-]返回顶部

  1. escape 与 unescape
  2. encodeURIComponent 与 decodeURIComponent (推荐)
  3. encodeURI 与 decodeURI
  4. escape 与 unescape
  5. encodeURIComponent 与 decodeURIComponent
  6. encodeURI 与 decodeURI
点击右上角即可分享
微信分享提示