在前後端交互中,URL 參數傳遞與資料編碼是常見議題。JavaScript 提供 escape、encodeURI、encodeURIComponent 三種編碼函式,而 C# 則有 HttpUtility.UrlEncode、Server.UrlEncode 等對應方法。本文系統整理三者的編碼範圍、適用場景及跨語言對照表,助您避開亂碼陷阱。
| 函式 | 不編碼字元數 | 不編碼字元清單 | 典型用途 |
|---|---|---|---|
escape |
69 個 | * + - . / @ _ 0-9 a-z A-Z |
歷史資料儲存(如 history 紀錄),非 ASCII 字元輸出 %uXXXX 格式 |
encodeURI |
82 個 | ! # $ & ' ( ) * + , - . / : ; = ? @ _ ~ 0-9 a-z A-Z |
整段 URL 跳轉(例:location.href = encodeURI(url)) |
encodeURIComponent |
71 個 | ! ' ( ) * - . _ ~ 0-9 a-z A-Z |
單一參數值編碼,防止 #、& 等特殊字元截斷 URL |
%uXXXX,其餘情況與另外兩者結果相同。:、/、?、# 等),適合對完整 URL 編碼。| JS 函式 | C# 編碼 | C# 解碼 | 備註 |
|---|---|---|---|
escape / unescape |
HttpUtility.UrlEncode |
HttpUtility.UrlDecode |
ASP.NET Core 建議使用 System.Net.WebUtility |
encodeURI / decodeURI |
HttpUtility.UrlEncode |
HttpUtility.UrlDecode |
實務上同 escape 對應,若需嚴格區分請自行實作 |
encodeURIComponent / decodeURIComponent |
HttpContext.Current.Server.UrlEncode |
HttpContext.Current.Server.UrlDecode |
最常用於 API 參數傳遞 |
// JS
location.href = encodeURI("https://cang.baidu.com/do/s?word=百度&ct=21");
// JS 動態產生帶參數的連結
document.write('<a href="https://passport.baidu.com/?logout&aid=7&u='
+ encodeURIComponent("https://cang.baidu.com/bruce42") + '">退出</a>');
// ASP.NET WebForms / MVC
string param = HttpContext.Current.Server.UrlDecode(Request.QueryString["u"]);
encodeURIComponent + decodeURIComponent。System.Net.WebUtility.UrlEncode/Decode 無需引用 System.Web,適合 .NET Core / Standard 專案。下表列出三種函式對常見特殊字元的編碼結果(✅ 表不編碼,🔴 表編碼):
| 字元 | escape | encodeURI | encodeURIComponent |
|---|---|---|---|
| 空格 | 🔴 %20 | 🔴 %20 | 🔴 %20 |
| # | 🔴 %23 | ✅ | 🔴 %23 |
| & | 🔴 %26 | ✅ | 🔴 %26 |
| = | 🔴 %3D | ✅ | 🔴 %3D |
| ? | 🔴 %3F | ✅ | 🔴 %3F |
| / | ✅ | ✅ | 🔴 %2F |
| @ | ✅ | ✅ | ✅ |
| 中文 | 🔴 %uXXXX | 🔴 %E4%B8%AD%E6%96%87 | 🔴 %E4%B8%AD%E6%96%87 |
掌握上述對照關係,即可在前後端協作中游刃有餘,徹底解決 URL 編碼亂碼問題。