1. 程式人生 > >escape()、encodeURI()、encodeURIComponent()區別詳解

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

ava 區別 enc esc http %x 其中 con sdn

前言

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