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
四、原文链接

作者:LiangSenCheng小森森 开源分享汇 公众号
出处:https://www.cnblogs.com/LiangSenCheng/p/17934730.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!