一句話區分如何使用encodeURI/decodeURI、encodeURIComponent/decodeURIComponent的實踐筆記

一句話區分如何使用encodeURI/decodeURI、encodeURIComponent/decodeURIComponent的實踐筆記


上次工做中遇到一個場景:傳參是一個完成的URL,而直接把URL傳過去明顯是行不通的,由於URL上有一些字符是有特殊意義的,並且也有可能url會存在中文等狀況,會變得很是不可控,因此URL須要字符編碼處理,再進行傳參。 以前沒有細想,可是爲了加深理解、記憶,我把這方面也寫下來。api

問題場景

訪問連接 https://www.xiaoyexiang.com/oauth2/authorize?redirect_uri={url}{url}是一個連接參數。應爲https://api.xiaoyexiang.com/api/weixin/login/oauth2?next=https://www.xiaoyexiang.com/classroom/homebash

剛開始我是使用了 encodeURI() 來處理URL,發現並無什麼效果:函數

let loginUrl = 'https://www.xiaoyexiang.com/oauth2/authorize?redirect_uri={redirect_uri}';
const originUri = `https://api.xiaoyexiang.com/api/weixin/login/oauth2?next=https://wwww.xiaoyexiang.com/l/s/352?_source=index_rcmd`;

const encodedUrl = encodeURI(originUri);

loginUrl = loginUrl.replace('{redirect_uri}', encodedUrl);

console.log(loginUrl); 
// https://www.xiaoyexiang.com/oauth2/authorize?redirect_uri=https://api.xiaoyexiang.com/api/weixin/login/oauth2?next=https://wwww.xiaoyexiang.com/l/s/352?_source=index_rcmd

console.log(encodedUrl);
// https://api.xiaoyexiang.com/api/weixin/login/oauth2?next=https://wwww.xiaoyexiang.com/l/s/352?_source=index_rcmd

複製代碼

後來查閱資料改用 encodeURIComponent()ui

let loginUrl = 'https://www.xiaoyexiang.com/oauth2/authorize?redirect_uri={redirect_uri}';
const originUri = `https://api.xiaoyexiang.com/api/weixin/login/oauth2?next=https://wwww.xiaoyexiang.com/l/s/352?_source=index_rcmd`;

const encodedUrl = encodeURIComponent(originUri);

loginUrl = loginUrl.replace('{redirect_uri}', encodedUrl);

console.log(loginUrl);
// https://www.xiaoyexiang.com/oauth2/authorize?redirect_uri=https%3A%2F%2Fapi.xiaoyexiang.com%2Fapi%2Fweixin%2Flogin%2Foauth2%3Fnext%3Dhttps%3A%2F%2Fwwww.xiaoyexiang.com%2Fl%2Fs%2F352%3F_source%3Dindex_rcmd

console.log(encodedUrl);
// https%3A%2F%2Fapi.xiaoyexiang.com%2Fapi%2Fweixin%2Flogin%2Foauth2%3Fnext%3Dhttps%3A%2F%2Fwwww.xiaoyexiang.com%2Fl%2Fs%2F352%3F_source%3Dindex_rcmd

複製代碼

問題解釋

encodeURI/decodeURI、encodeURIComponent/decodeURIComponent 這四個方法的用處

都是用來編碼和解碼URI的。編碼

encodedURI

  • 函數經過將特定字符的每一個實例替換爲一個、兩個、三或四轉義序列來對統一資源標識符 (URI) 進行編碼 (該字符的 UTF-8 編碼僅爲四轉義序列)由兩個 "代理" 字符組成)。
  • encodeURI 自身沒法產生能適用於HTTP GET 或 POST 請求的URI,例如對於 XMLHTTPRequests, 由於 "&", "+", 和 "=" 不會被編碼,然而在 GET 和 POST 請求中它們是特殊字符。然而encodeURIComponent這個方法會對這些字符編碼。

decodeURI

函數解碼一個由encodeURI 先前建立的統一資源標識符(URI)或相似的例程。url

encodeURIComponent

  • 是對統一資源標識符(URI)的組成部分進行編碼的方法。它使用一到四個轉義序列來表示字符串中的每一個字符的UTF-8編碼(只有由兩個Unicode代理區字符組成的字符才用四個轉義字符編碼)。
  • 轉義除了字母、數字、().!~*'-_以外的全部

decodeURIComponent

方法用於解碼由 encodeURIComponent 方法或者其它相似方法編碼的部分統一資源標識符(URI)。spa

我的總結

當你須要轉碼/解碼的URL是須要一個完整、可直接訪問的URL時,應該使用encodeURI/decodeURI; 當你須要轉碼/解碼的URL是做爲連接的一部分,好比用做參數的狀況,應該使用encodeURIComponent/decodeURIComponentssr

相關文章
相關標籤/搜索