JS19 encodeURI和encodeURIComponent
阿新 • • 發佈:2018-12-03
統一資源識別符號,或叫做URI,是用來標識網際網路上的資源(例如,網頁或檔案)和怎樣訪問這些資源的傳輸協議(例如,HTTP 或 FTP)的字串
encodeURI()
和encodeURIComponent()
方法可以對URI進行編碼,編碼為UTF-8編碼,前者不會對屬於URI的特殊字元進行編碼,比如冒號、正斜槓等,而後者會對所有發現的特殊字元進行編碼
encodeUR
會替換所有的字元,但不包括以下字元,即使它們具有適當的UTF-8轉義序列:
型別 | 包含 |
---|---|
保留字元 | / ? : @ & = + $ |
非轉義的字元 | 字母 數字 - _ . ! ~ * ' ( ) |
數字符號 | # |
let str = 'http://www.baidu.com/我'
encodeURI(str)
// "http://www.baidu.com/%E6%88%91"
encodeURIComponent(str)
// "http%3A%2F%2Fwww.baidu.com%2F%E6%88%91"
請注意,encodeURI
自身無法產生能適用於HTTP協議中GET或POST請求的URI,例如對於XMLHTTPRequests, 因為&
+
, 和=
不會被編碼,然而在GET和POST請求中它們是特殊字元。然而encodeURIComponent
這個方法會對這些字元編碼。
所以一般來說,使用encodeURIComponent()
的場景是對URI中某一段(一般是查詢引數)進行處理,使用相對更加頻繁
var test = 'http://www.baidu.com/?type=a&name=zhou'; console.log(encodeURI(test), 'encodeURI'); // http://www.baidu.com/?type=a&name=zhou console.log(encodeURIComponent(test), 'encodeURIComponent'); // http%3A%2F%2Fwww.baidu.com%2F%3Ftype%3Da%26name%3Dzhou
decodeURI
、decodeURIComponent
用來解碼,用法類似。
參考
- MDN - encodeURI()
- JavaScript高階程式設計(第3版)