向基礎牢固得像呼吸一樣自然的目標出發 沖鴨,雖然很早之前就學過,但是不久就忘記了,誠然,溫故而知新,果然沒錯!
escape 和 unescape
escape()不能直接用於URL編碼,它的真正作用是返回一個字符的Unicode編碼值
它的具體規則是,除了ASCII字母、數字、標點符號"@ * _ + - . /"以外,對其他所有字符進行編碼。在u0000到u00ff之間的符號被轉成%xx的形式,其余符號被轉成%uxxxx的形式。對應的解碼函數是unescape()。
還有兩個點需要注意
- 首先,無論網頁的原始編碼是什么,一旦被Javascript編碼,就都變為unicode字符。也就是說,Javascipt函數的輸入和輸出,默認都是Unicode字符。這一點對下面兩個函數也適用。
- 其次,escape()不對"+"編碼。但是我們知道,網頁在提交表單的時候,如果有空格,則會被轉化為+字符。服務器處理數據的時候,會把+號處理成空格。所以,使用的時候要小心。
// escape()編碼: const time = 2018-02-09 const tile = '63元黑糖顆粒固飲' let url = “http://localhost:8080/index.html?time="+escape(time)+"&title="+escape(tile) //地址欄顯示結果:“http://localhost:8080/index.html?time=2018-01-09&title=63%u5143%u9ED1%u7CD6%u9897%u7C92%u56FA%u996E"
// unescape()解碼: let url = “http://localhost:8080/index.html?time="+unescape(2018-01-09)+"&title="+unescape(63%u5143%u9ED1%u7CD6%u9897%u7C92%u56FA%u996E) // 地址欄顯示結果: “http://localhost:8080/index.html?time=2018-01-09&title=63元黑糖顆粒固飲"
encodeURI 和 decodeURI
encodeURI()是Javascript中真正用來對URL編碼的函數。
它用於對URL的組成部分進行個別編碼,除了常見的符號以外,對其他一些在網址中有特殊含義的符號"; / ? : @ & = + $ , #",也不進行編碼。編碼后,它輸出符號的utf-8形式,並且在每個字節前加上%。
它對應的解碼函數是decodeURI(),需要注意的是,它不對單引號'編碼。
let url = "http://localhost:8080/index.html?time=2018-01-09&title=63元黑糖顆粒固飲" encodeURI()編碼: let encodeURI_url = encodeURI(url) = "http://localhost:8080/index.html?time=2018-01-09&title=63%E5%85%83%E9%BB%91%E7%B3%96%E9%A2%97%E7%B2%92%E5%9B%BA%E9%A5%AE" decodeURI()解碼: decodeURI(encodeURI_url )= “http://localhost:8080/index.html?time=2018-01-09&title=63元黑糖顆粒固飲”
encodeURIComponent 和 decodeURIComponent
與encodeURI()的區別是,它用於對整個URL進行編碼。"; / ? : @ & = + $ , #",這些在encodeURI()中不被編碼的符號,在encodeURIComponent()中統統會被編碼。
它對應的解碼函數是decodeURIComponent()。
let url = "http://localhost:8080/index.html?time=2018-01-09&title=63元黑糖顆粒固飲" encodeURIComponent ()編碼: let encodeURIComponent _url = encodeURIComponent (url) = http%3A%2F%2Flocalhost%3A8080%2Findex.html%3Ftime%3D2018-01-09%26title%3D63%E5%85%83%E9%BB%91%E7%B3%96%E9%A2%97%E7%B2%92%E5%9B%BA%E9%A5%AE decodeURIComponent()解碼: decodeURIComponent(encodeURIComponent _url )= “http://localhost:8080/index.html?time=2018-01-09&title=63元黑糖顆粒固飲”
本文轉載於https://segmentfault.com/a/1190000013236956
點贊👍+關注我吧~
我只想成為更好的自己
