本文介绍 URL 编码的原理和常见问题。
为什么需要 URL 编码
URL 只能包含 ASCII 字符,对于以下情况需要编码:
- 非 ASCII 字符:中文、日文等
- 特殊字符:
&、=、?、# 等有特殊含义的字符
- 空格:需要转换为
%20 或 +
JavaScript 编码函数
encodeURI vs encodeURIComponent
| 函数 |
用途 |
不编码的字符 |
encodeURI |
编码完整 URL |
; , / ? : @ & = + $ # |
encodeURIComponent |
编码 URL 参数值 |
仅保留字母数字和 - _ . ! ~ * ' ( ) |
使用示例
1 2 3 4 5 6 7
| encodeURI("https://example.com/搜索?q=关键词")
encodeURIComponent("name=张三&age=18")
|
何时使用哪个
1 2 3 4 5
| const url = "https://api.com/search?q=" + encodeURIComponent(userInput);
const url = "https://api.com/search?q=" + encodeURI(userInput);
|
常见编码问题
乱码问题
确保前后端使用相同的编码(通常是 UTF-8):
解码函数
1 2
| decodeURI(encodedURI) decodeURIComponent(encodedComponent)
|
参考: 阮一峰 - 关于URL编码