把中文或特殊字元放進 URL 時必須先編碼。JavaScript 提供了三個相關函式,行為差異不小,選錯很容易產生非預期的結果。
encodeURI():把字串編碼為 URIencodeURIComponent():把字串編碼為 URI 元件escape():對字串進行編碼(已廢棄)var str = "https://localhost:8080/Product/index?id=123&attr=456&area=中國"; console.log(encodeURI(str)); // https://localhost:8080/Product/index?id=123&attr=456&area=%E4%B8%AD%E5%9B%BD console.log(encodeURIComponent(str)); // http%3A%2F%2Flocalhost%3A8080%2FProduct%2Findex%3Fid%3D123%26attr%3D456%26area%3D%E4%B8%AD%E5%9B%BD console.log(escape(str)); // http%3A//localhost%3A8080/Product/index%3Fid%3D123%26attr%3D456%26area%3D%u4E2D%u56FD
encodeURI 不會編碼 :、/、?、&、= 這些在 URI 中具有分隔作用的保留字元,因為它的設計前提是「傳入的是一個完整的 URI」,必須保留其結構。
encodeURIComponent 則會把這些字元一併編碼,因為它的前提是你傳入的是「URI 中的某一個元件值」,不該讓值裡的 & 被誤認為參數分隔符。
escape 的規則最古老:除了 ASCII 中的字母、數字與 * @ - _ + . / 之外全部編碼,中文會被轉成 %uXXXX 這種非標準格式,伺服器端無法正確解讀。
escape 與 unescape 已從標準中移除,請不要再用。選擇很簡單:
encodeURIencodeURIComponent,這也是絕大多數場景的正確選擇var base = "https://example.com/search"; var q = "JavaScript 教學 & 範例"; var url = base + "?q=" + encodeURIComponent(q);
若需要更完整的 RFC 3986 相容編碼(把 !、'、(、)、* 也編碼進去),可以在 encodeURIComponent 外再套一層 replace。解碼則一律對應使用 decodeURIComponent。