escape()、encodeURI()、encodeURIComponent()區別詳解

來源:互聯網
上載者:User

標籤:sci   數字   pre   關係   col   https   bar   div   esc   

前言

JavaScript中有三個可以對字串編碼的函數,分別是:escape,encodeURI,encodeURIComponent,相應3個解碼函數:unescape,decodeURI,decodeURIComponent 。

 escape()和它們不是同一類

簡單來說,escape()是對字串(string)進行編碼(而另外兩種是對URL),作用是讓它們在所有電腦上可讀。 
編碼之後的效果是%XX或者%uXXXX這種形式。 其中 ASCII字母、數字、@*/+ ,這幾個字元不會被編碼,其餘的都會。 
最關鍵的是,當你需要對URL編碼時,請忘記這個方法,這個方法是針對字串使用的,不適用於URL。

escape(‘編碼‘)  //"%u7F16%u7801"unescape(‘%u7F16%u7801‘)  //"編碼"

 

 

 

最常用的encodeURI()和encodeURIComponent()

對URL編碼是常見的事,所以這兩個方法應該是實際中要特別注意的。 
它們都是編碼URL,唯一區別就是編碼的字元範圍,其中: 
encodeURI方法不會對下列字元編碼 ASCII字母、數字、[email protected]#$&*()=:/,;?+’ 
encodeURIComponent方法不會對下列字元編碼 ASCII字母、數字、~!*()’ 
所以encodeURIComponent比encodeURI編碼的範圍更大。

 

實際例子來說,encodeURIComponent會把http://  編碼成  http%3A%2F%2F 而encodeURI卻不會。encodeURI(‘https://www.baidu.com/‘)           //"https://www.baidu.com/"encodeURIComponent(‘https://www.baidu.com/‘)  //"https%3A%2F%2Fwww.baidu.com%2F"
 最重要的,我該什麼場合用什麼方法

區別上面說的很清楚了,接下來從實際例子來說說把。 
1、如果只是編碼字串,不和URL有半毛錢關係,那麼用escape。 
2、如果你需要編碼整個URL,然後需要使用這個URL,那麼用encodeURI。 
3、當你需要編碼URL中的參數的時候,那麼encodeURIComponent是最好方法。

var a = "http://blog.csdn.net/?ref=toolbar_logo&test=測試"escape(a)  //"http%3A//blog.csdn.net/%3Fref%3Dtoolbar_logo%26test%3D%u6D4B%u8BD5"unescape("http%3A//blog.csdn.net/%3Fref%3Dtoolbar_logo%26test%3D%u6D4B%u8BD5")//"http://blog.csdn.net/?ref=toolbar_logo&test=測試"encodeURI(a)  //"http://blog.csdn.net/?ref=toolbar_logo&test=%E6%B5%8B%E8%AF%95"decodeURI("http://blog.csdn.net/?ref=toolbar_logo&test=%E6%B5%8B%E8%AF%95")//"http://blog.csdn.net/?ref=toolbar_logo&test=測試"encodeURIComponent(a)//"http%3A%2F%2Fblog.csdn.net%2F%3Fref%3Dtoolbar_logo%26test%3D%E6%B5%8B%E8%AF%95"decodeURIComponent("http%3A%2F%2Fblog.csdn.net%2F%3Fref%3Dtoolbar_logo%26test%3D%E6%B5%8B%E8%AF%95")//"http://blog.csdn.net/?ref=toolbar_logo&test=測試"

 

escape()、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.