JS對url進行編碼和解碼(三種方式)

escape 和 unescape

escape()不能直接用於URL編碼,它的真正做用是返回一個字符的Unicode編碼值html

它的具體規則是,除了ASCII字母、數字、標點符號"@ * _ + - . /"之外,對其餘全部字符進行編碼。在u0000到u00ff之間的符號被轉成%xx的形式,其他符號被轉成%uxxxx的形式。對應的解碼函數是unescape()。服務器

還有兩個點須要注意函數

  1. 首先,不管網頁的原始編碼是什麼,一旦被Javascript編碼,就都變爲unicode字符。也就是說,Javascipt函數的輸入和輸出,默認都是Unicode字符。這一點對下面兩個函數也適用。
  2. 其次,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()url

須要注意的是,它不對單引號'編碼。code

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()。htm

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元黑糖顆粒固飲」
相關文章
相關標籤/搜索