標籤: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()區別詳解