URL 編解碼完全指南:百分號編碼的原理與實戰

加密編碼(更新於 2026年5月27日)

URL 結構回顧

https://user:pass@www.example.com:8080/path/to/page?name=张三&age=25#section
└──┬──┘ └────┬────┘ └──────┬──────┘└─┬─┘└────┬─────┘└──────┬──────┘└──┬──┘
  scheme   userinfo     host      port    path        query     fragment

只有 path、query、fragment 部分需要編碼。scheme 和 host 有各自的規則。


為什麼需要 URL 編碼?

URL 只能包含 ASCII 可列印字元。以下字元必須編碼:

字元 編碼 原因
空格 %20+ 不允許裸空格
中文「张三」 %E5%BC%A0%E4%B8%89 非 ASCII
& %26 query 分隔符
= %3D key=value 分隔符
# %23 fragment 標識
? %3F query 開始
/ %2F path 分隔符

使用工具庫 URL 編解碼

操作步驟

  1. 開啟 URL 編解碼工具
  2. 輸入 URL 或文字
  3. 選擇 encode 或 decode
  4. 查看結果

encodeURI vs encodeURIComponent

函式 不編碼 適用
encodeURI() : / ? # [ ] @ ! $ & ' ( ) * + , ; = 完整 URL
encodeURIComponent() A-Z a-z 0-9 - _ . ! ~ * ' ( ) URL 參數值
const base = 'https://example.com/search';

// ✅ 編碼參數值
const url = `${base}?q=${encodeURIComponent('hello world')}`;
// → https://example.com/search?q=hello%20world

// ❌ 編碼整個 URL
const wrong = encodeURIComponent('https://example.com/search?q=test');
// → https%3A%2F%2Fexample.com%2Fsearch%3Fq%3Dtest

實戰場景

中文 query 參數

原始: https://search.com/q=前端开发
編碼: https://search.com/q=%E5%89%8D%E7%AB%AF%E5%BC%80%E5%8F%91

解析 URL 參數

使用 URL 解析工具 分解 URL 並展示 query 參數表:

輸入: https://api.com/users?name=张三&role=admin&page=1
輸出:
  name  = 张三
  role  = admin
  page  = 1

國際化網域 (IDN)

中文網域「工具库.com」的 Punycode 編碼:

工具库.com → xn--6qq986b3xl.com

使用 Punycode 工具 互轉。

Base64 編碼 URL 參數

有時需要將 JSON 物件編碼為 URL 參數:

{"user":"admin","role":"editor"}
  → Base64 → eyJ1c2VyIjoiYWRtaW4iLCJyb2xlIjoiZWRpdG9yIn0=
  → URL encode → eyJ1c2VyIjoiYWRtaW4iLCJyb2xlIjoiZWRpdG9yIn0%3D

常見錯誤

雙重編碼

原始: hello world
一次編碼: hello%20world  ✅
兩次編碼: hello%2520world  ❌ (解碼一次得到 hello%20world)

編碼整個 URL

只對參數值使用 encodeURIComponent,不要對完整 URL 編碼。

空格用 + 還是 %20

  • Query 參數中:+%20 等價
  • Path 中:只能用 %20
  • 建議統一使用 %20

總結

URL 編碼是 Web 開發的基本功。理解 encodeURI 與 encodeURIComponent 的差異、中文參數的 UTF-8 編碼,以及國際化網域的 Punycode 轉換,能避免大量除錯時間。工具庫提供 URL 編解碼URL 解析Punycode 工具。

#URL#编解码#百分号编码#查询参数#Web