什么是 URL 编码?
URL 编码(也称为百分号编码)是一种将 URL 中的特殊字符转换为 % 后跟两位十六进制数的格式。URL 只允许使用 ASCII 字母、数字和部分特殊字符,其他字符(如中文、空格)必须被编码。
两对标准 API(编码与解码一一对应):
- URL 编码 / URL 解码:
encodeURI()/decodeURI()。保留 URL 结构字符(如 /、?、#、&、=),适合处理完整 URL;已编码的 %2F、%3F、%3D 解码后仍会保留 - URI 组件编码 / URI 组件解码:
encodeURIComponent()/decodeURIComponent()。处理所有非字母数字字符,适合查询参数、路径片段;会把 %2F→/、%3F→?、%3D→= 全部还原
例如,空格在 URL 编码中变为 %20,中文 "你好" 变为 %E4%BD%A0%E5%A5%BD。
What is URL Encoding?
URL encoding (also known as percent-encoding) converts special characters in URLs into a format preceded by % followed by two hexadecimal digits. URLs only allow ASCII letters, digits, and a few special characters — all other characters (including Chinese characters and spaces) must be encoded.
Two standard API pairs (encode and decode match 1:1):
- URL Encode / URL Decode —
encodeURI()/decodeURI(). Preserves URL structure characters (/, ?, #, &, =); suitable for a full URL. Encoded %2F, %3F, and %3D stay encoded after decode. - URI Component Encode / URI Component Decode —
encodeURIComponent()/decodeURIComponent(). Encodes all non-alphanumeric characters; suitable for query values and path segments. Fully restores %2F→/, %3F→?, %3D→=.
For example, a space becomes %20, and the Chinese characters "你好" become %E4%BD%A0%E5%A5%BD.