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"
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元黑糖顆粒固飲”