本文介绍 URL 编码的原理和常见问题。

为什么需要 URL 编码

URL 只能包含 ASCII 字符,对于以下情况需要编码:

  1. 非 ASCII 字符:中文、日文等
  2. 特殊字符&=?# 等有特殊含义的字符
  3. 空格:需要转换为 %20+

JavaScript 编码函数

encodeURI vs encodeURIComponent

函数 用途 不编码的字符
encodeURI 编码完整 URL ; , / ? : @ & = + $ #
encodeURIComponent 编码 URL 参数值 仅保留字母数字和 - _ . ! ~ * ' ( )

使用示例

1
2
3
4
5
6
7
// 编码完整 URL(保留 URL 结构字符)
encodeURI("https://example.com/搜索?q=关键词")
// 结果: "https://example.com/%E6%90%9C%E7%B4%A2?q=%E5%85%B3%E9%94%AE%E8%AF%8D"

// 编码参数值(更严格)
encodeURIComponent("name=张三&age=18")
// 结果: "name%3D%E5%BC%A0%E4%B8%89%26age%3D18"

何时使用哪个

1
2
3
4
5
// 正确:用 encodeURIComponent 编码参数值
const url = "https://api.com/search?q=" + encodeURIComponent(userInput);

// 错误:用 encodeURI 可能导致参数注入
const url = "https://api.com/search?q=" + encodeURI(userInput);

常见编码问题

乱码问题

确保前后端使用相同的编码(通常是 UTF-8):

1
<meta charset="UTF-8">

解码函数

1
2
decodeURI(encodedURI)
decodeURIComponent(encodedComponent)

参考: 阮一峰 - 关于URL编码