← 返回工具箱
% URL编码解码
模式: 等待操作

相关知识

URL 编码规则

URL 编码(Percent Encoding)将特殊字符替换为 % 加两位十六进制数表示的字节值。

字符编码说明
空格%20 或 +在查询字符串中空格也可用 + 表示
!%21感叹号
#%23哈希符,URL 中用于锚点
$%24美元符
&%26参数分隔符,需编码
=%3D键值对分隔符,需编码
?%3F查询字符串开始标记
/%2F路径分隔符(encodeURIComponent 编码,encodeURI 不编码)
中文"你"%E4%BD%A0UTF-8 多字节编码

encodeURI vs encodeURIComponent

函数不编码的字符适用场景
encodeURIA-Z a-z 0-9 - _ . ! ~ * ' ( ) ; / ? : @ & = + $ , #对完整 URL 编码,保留 URL 结构字符
encodeURIComponentA-Z a-z 0-9 - _ . ! ~ * ' ( )对 URL 参数值编码,编码所有结构字符

常见使用场景

场景推荐函数示例
编码查询参数值encodeURIComponentq=encodeURIComponent("你好") → q=%E4%BD%A0%E5%A5%BD
编码完整 URLencodeURI保留 ://、/ 等结构
解码后端传来的参数decodeURIComponent%E4%BD%A0%E5%A5%BD → 你好
表单数据提交application/x-www-form-urlencoded空格编码为 +,其余用 %XX

RFC 3986 保留字符

RFC 3986 将 URL 字符分为两类:

提示:在构建 URL 时,应对每个参数值单独使用 encodeURIComponent 编码,然后再拼接 URL,而不是对整个 URL 使用 encodeURI,以避免参数中的特殊字符破坏 URL 结构。
URL = scheme "://" authority path ["?" query] ["#" fragment]
例:https://example.com/path?key=value#section