本文對 JavaScript 與 C# 的編碼解碼方法進行了詳細對照,需要的朋友可以參考,希望能對大家有所幫助。
先了解三個編碼函數不編碼的字符範圍:
escape 不編碼 69 個字符:* + - . / @ _ 0-9 a-z A-Z;
encodeURI 不編碼 82 個字符:! # $ & ' ( ) * + , - . / : ; = ? @ _ ~ 0-9 a-z A-Z;
encodeURIComponent 不編碼 71 個字符:! ' ( ) * - . _ ~ 0-9 a-z A-Z。
對於 0-255 以外的 unicode 值,escape 編碼時輸出 %u**** 格式,其他情況下三者編碼結果相同。
JavaScript 中使用數據時可用 escape,例如收藏中的 history 記錄;解碼使用 unescape。C# 對應 HttpUtility.UrlEncode 與 HttpUtility.UrlDecode。
進行 URL 跳轉時可整體使用 encodeURI,例如:
Location.href = encodeURI("https://cang.baidu.com/do/s?word=百度&ct=21");
解碼使用 decodeURI(),C# 對應 decodeURIComponent。
傳遞參數時需要使用 encodeURIComponent,這樣組合的 URL 才不會被 # 等特殊字符截斷:
<script language="javascript">
document.write('<a href="https://passport.baidu.com/?logout&aid=7&u='
+ encodeURIComponent("https://cang.baidu.com/bruce42")
+ '">退出</a>');
</script>
解碼使用 decodeURIComponent(),C# 對應 [HttpContext.Current.]Server.UrlDecode 與 Server.UrlEncode。
簡單總結:escape 適用於一般數據編碼,encodeURI 適用於整個 URL 跳轉,encodeURIComponent 則適用於傳遞單個參數,三者各司其職。