URL 編碼完全指南:百分比編碼原理與常見問題解決
深入了解 URL 編碼(百分比編碼)的原理、為什麼需要它、encodeURI 和 encodeURIComponent 的差異,以及常見的編碼問題和解決方案。
本文介紹的工具:URL 編碼/解碼器
什麼是 URL 編碼?
URL 編碼(URL Encoding),也稱為百分比編碼(Percent-Encoding),是一種將特殊字元轉換為 %XX 格式的機制,其中 XX 是字元的十六進位 ASCII 碼。
空格 → %20
中文「你好」→ %E4%BD%A0%E5%A5%BD
為什麼需要 URL 編碼?
URL 只能包含 ASCII 字元集中的特定字元。以下字元在 URL 中有特殊含義:
| 字元 | URL 中的用途 |
|---|---|
? |
查詢字串開始 |
& |
參數分隔 |
= |
鍵值分隔 |
# |
片段標識 |
/ |
路徑分隔 |
% |
編碼前綴 |
當這些字元出現在參數值中時,必須進行編碼以避免歧義。
JavaScript 中的編碼函數
encodeURI vs encodeURIComponent
| 函數 | 用途 | 不編碼的字元 |
|---|---|---|
encodeURI |
編碼完整 URL | : / ? # [ ] @ ! $ & ' ( ) * + , ; = |
encodeURIComponent |
編碼 URL 組件 | - _ . ! ~ * ' ( ) |
const url = "https://example.com/search?q=Hello World&lang=中文";
encodeURI(url);
// "https://example.com/search?q=Hello%20World&lang=%E4%B8%AD%E6%96%87"
// ✅ 保留 URL 結構
encodeURIComponent(url);
// "https%3A%2F%2Fexample.com%2Fsearch%3Fq%3DHello%20World%26lang%3D%E4%B8%AD%E6%96%87"
// ❌ 破壞 URL 結構
正確用法
// ✅ 編碼參數值
const query = encodeURIComponent("Hello World & 中文");
const url = `https://example.com/search?q=${query}`;
// ✅ 編碼完整 URL(保留結構)
const fullUrl = encodeURI("https://example.com/path/中文頁面");
常見問題
空格的編碼:%20 還是 +?
- %20:標準的百分比編碼
- +:僅在
application/x-www-form-urlencoded格式中使用
// URL 路徑中使用 %20
"https://example.com/my%20file.pdf"
// 查詢字串中 + 和 %20 都可以
"https://example.com/search?q=hello+world"
"https://example.com/search?q=hello%20world"
雙重編碼問題
當已經編碼的字串被再次編碼時,會產生雙重編碼:
原始:Hello World
第一次:Hello%20World
第二次:Hello%2520World ← 錯誤!
解決方案:在編碼前先解碼,確保不會重複編碼。
中文 URL 的處理
現代瀏覽器會自動處理中文 URL 的顯示,但在程式中傳遞時仍需編碼:
// 瀏覽器顯示:https://example.com/中文
// 實際傳輸:https://example.com/%E4%B8%AD%E6%96%87
實用工具推薦
使用我們的 URL 編碼工具 可以快速進行 URL 編碼和解碼,支援完整 URL 和 URL 組件的處理。