escape、encodeURI、encodeURIComponent區別

前言

JS 中有三個能夠對字符串編碼的函數,分別是: escape,encodeURI,encodeURIComponentgit

escape()

一般用於對字符串編碼,不適用於對 URL 編碼github

除了 ASCII 字母、數字和特定的符號外,對傳進來的字符串所有進行轉義編碼,所以若是想對 URL 編碼,最好不要使用此方法。函數

escape 不會編碼的字符有 69 個:* + - . / @ _ 0-9 a-z A-Z編碼

固然若是沒有必要,不要使用 escape。url

encodeURI()

encodeURI()不會進行編碼的字符有 82 個 : ; , / ? : @ & = + $ - _ . ! ~ * ' ( ) # 0-9 a-z A-Zcode

使用encodeURI()編碼後的結果是除了空格以外的其餘字符都原封不動,只有空格被替換成了%20,encodeURI主要用於直接賦值給地址欄。blog

encodeURIComponent()

encodeURIComponent:不會進行編碼的字符有 71 個:! ' ( ) * - . _ ~ 0-9 a-z A-Z字符串

encodeURIComponentencodeURI編碼的範圍更大,如encodeURIComponent會把 http:// 編碼成 http%3A%2F%2FencodeURI不解碼維持http://get

encodeURIComponent() 方法在編碼單個 URIComponent(指請求參數)應當是最經常使用的,它能夠將參數中的中文、特殊字符進行轉義,而不會影響整個 URLit

如何選擇和使用三個函數

  • 若是隻是編碼字符串,和 URL 沒有關係,才能夠用escape。(但它已經被廢棄,儘可能避免使用,應用encodeURIencodeURIComponent
  • 若是須要編碼整個 URL,而後須要使用這個 URL,那麼用encodeURI
  • 若是須要編碼 URL 中的參數的時候,那麼encodeURIComponent是最好方法。
encodeURI("https://github.com/Jacky-Summer/test params");

編碼後變成

https://github.com/Jacky-Summer/test%20params

其中空格被編碼成了%20,而若是是用encodeURIComponent

https%3A%2F%2Fgithub.com%2FJacky-Summer%2Ftest%20params

/ 都被編碼了,整個 URL 已經無法用了。

當編碼 URL 的特殊參數時:

// 參數的 / 是須要編碼的,而若是是 encodeURI 編碼則不編碼 / 就會出問題
let param = "https://github.com/Jacky-Summer/";
param = encodeURIComponent(param);
const url = "https://github.com?param=" + param;
console.log(url) // "https://github.com?param=https%3A%2F%2Fgithub.com%2FJacky-Summer%2F"

參考:https://www.zhihu.com/questio...


相關文章
相關標籤/搜索