decodeURI和 decodeURIComponent以及encodeURI和encodeURIComponent的區別

來源:互聯網
上載者:User

標籤:blog   http   使用   ar   java   資料   div   問題   c   

url傳遞參數這是很常見資料傳遞方式,但如果不注意也是很容易出現問題的。

最常見的就是url傳遞中文亂碼了以及空格被轉碼,而要避免這種問題出現的最佳解決方案是傳遞前編碼,接收資料後解碼。編碼我們用encodeURI和encodeURIComponent,解碼我們用decodeURI和decodeURIComponent。

encodeURI() 把字串編碼為 URI。(對應decodeURI)
encodeURIComponent() 把字串編碼為 URI 組件。
decodeURI() 解碼某個編碼的 URI。對應encodeURI)
decodeURIComponent() 解碼一個編碼的 URI 組件。(對應encodeURIComponent)

這兩種轉碼和解碼方式具體有什麼區別呢?看下面幾行代碼運行結果就知道了:

var urlStr="http://www.coolfish.cn/tag/url中文亂碼";  var enURI=encodeURI(urlStr);  var deURI=decodeURI(urlStr);   var enURIC=encodeURIComponent(urlStr);  var deURIC=decodeURIComponent(urlStr);console.log("初始URL:"+urlStr);console.log("encodeURI轉碼:"+enURI);console.log("decodeURI解碼:"+deURI);console.log("encodeURIComponent轉碼:"+enURIC);console.log("decodeURIComponent解碼:"+deURIC);

  運行結果:

初始URL:http://www.coolfish.cn/tag/url中文亂碼
encodeURI轉碼:http://www.coolfish.cn/tag/url%E4%B8%AD%E6%96%87%E4%B9%B1%E7%A0%81
decodeURI解碼:http://www.coolfish.cn/tag/url中文亂碼
encodeURIComponent轉碼:http%3A%2F%2Fwww.coolfish.cn%2Ftag%2Furl%E4%B8%AD%E6%96%87%E4%B9%B1%E7%A0%81
decodeURIComponent解碼:http://www.coolfish.cn/tag/url中文亂碼

可以看到encodeURIComponent轉碼的時候會把uri進行編碼(url中的://轉碼了)。

當我們的url傳遞類似callbackURL的參數的時候,最好是使用encodeURIComponent和decodeURIComponent來編碼和轉碼。

decodeURI和 decodeURIComponent以及encodeURI和encodeURIComponent的區別

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.