HTML URL 编码
URL编码(Percent-Encoding)将URL中的特殊字符转换为可在互联网上安全传输的格式。每个字符被替换为%XX格式的百分号编码。
为什么需要URL编码?
URL中有些字符有特殊含义,有些字符在URL中是非法的,需要编码才能正确传输。
注意
空格在URL中是非法的,必须编码为 %20 或 + 号。
常用字符编码
| 原始字符 | 编码后 | 说明 |
|---|---|---|
| 空格 | %20 或 + | 最常见需要编码的字符 |
| ! | %21 | 感叹号 |
| # | %23 | 井号(锚点标记) |
| % | %25 | 百分号本身 |
| & | %26 | 与号 |
| = | %3D | 等号 |
| ? | %3F | 问号(查询字符串开始) |
JavaScript中的URL编码
// 编码整个URL(保留URL特殊字符)
encodeURI("https://example.com/你好")
// 结果: "https://example.com/%E4%BD%A0%E5%A5%BD"
// 编码URL参数(编码所有特殊字符)
encodeURIComponent("你好&世界")
// 结果: "%E4%BD%A0%E5%A5%BD%26%E4%B8%96%E7%95%8C"
// 解码
decodeURI("https://example.com/%E4%BD%A0%E5%A5%BD")
decodeURIComponent("%E4%BD%A0%E5%A5%BD") encodeURI vs encodeURIComponent
encodeURI()- 不编码URL中的特殊字符(如 : / ? #)encodeURIComponent()- 编码所有字符,包括URL特殊字符
编码示例
<!-- 原始URL -->
https://example.com/search?keyword=hello world
<!-- 编码后 -->
https://example.com/search?keyword=hello%20world
<!-- 中文编码 -->
https://example.com/你好
https://example.com/%E4%BD%A0%E5%A5%BD