DIV CSS 佈局教程網

JavaScript 三種字串編碼函式的差異實測
編輯:JavaScript綜合知識     

在客戶端處理 URL 時,escape()、encodeURI()、encodeURIComponent() 這 trio 經常被混用。它們的差別不只是「編碼強度」,更關鍵的是「哪些字元會被保留」。

官方定義

· encodeURI():把字串編碼為 URI。
· encodeURIComponent():把字串編碼為 URI 元件。
· escape():對字串進行編碼(已廢棄)。

實測比較

var str = "https://localhost:8080/Product/index?id=123&attr=456&area=中國";

console.log(encodeURI(str));
console.log(encodeURIComponent(str));
console.log(escape(str));

輸出結果:

// encodeURI
https://localhost:8080/Product/index?id=123&attr=456&area=%E4%B8%AD%E5%9B%BD

// encodeURIComponent
http%3A%2F%2Flocalhost%3A8080%2FProduct%2Findex%3Fid%3D123%26attr%3D456%26area%3D%E4%B8%AD%E5%9B%BD

// escape
http%3A//localhost%3A8080/Product/index%3Fid%3D123%26attr%3D456%26area%3D%u4E2D%u56FD

差異在哪裡

encodeURI 不會編碼在 URI 中擔任分隔角色的字元,也就是 : / ? & = + # 等。它保留 URI 的整體結構,適合處理「一整個完整網址」。encodeURIComponent 則會把這些一併編碼,適合處理「要放進參數值裡的一段文字」。

escape 的行為又不同:? : & 被編碼了,/ 卻沒有。依 MDN 的說明,escape 只對 ASCII 中字母、數字與 * @ - _ + . / 以外的字元編碼。更關鍵的差異在中文處理上——它採用 %uXXXX 這種非標準格式(例如 %u4E2D%u56FD),而 UTF-8 的 %E4%B8%AD%E5%9B%BD 才是 URL 標準。這意味著 escape 編碼的結果在伺服器端無法被正確解讀,MDN 也明確建議不要使用它,改用 encodeURI 或 encodeURIComponent。

實務選擇

口訣很簡單:編碼整個 URL 用 encodeURI,編碼單一參數值用 encodeURIComponent,escape 一律不用。若想讓空格顯示成 %20 而非 +,encodeURIComponent 正是你要的;反之表單送出時的 application/x-www-form-urlencoded 才用 + 代表空格。

另外,解碼端也有對應函式:decodeURI 與 decodeURIComponent。兩者必須成對使用,用 encodeURI 編碼的內容若拿 decodeURIComponent 解,遇到保留字元時行為可能不如預期。而在現代專案中,若使用 URLSearchParams 或 URL 建構式來組裝查詢字串,編碼與解碼都會自動處理,不必手動呼叫這些函式。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved