encodeURI和encodeURIComponent的區別
阿新 • • 發佈:2018-12-21
var test1="http://www.w3school.com.cn/My first/?uname=aa&&pwd=123456";
console.log(encodeURI(test1));
console.log(encodeURIComponent(test1));
var test2="http://www.w3school.com.cn/My first/#qpp";
console.log(encodeURI(test2));
console.log(encodeURIComponent(test2));
一、區別:
encodeURI是對url中的查詢字串部分進行轉義
encodeURIComponent對整個url進行轉義,包括空格、英文冒號、斜槓等
至於decodeURI和decodeURIComponent,只要知道decodeURI和encodeURI是互逆操作,decodeURIComponent和encodeURIComponent是互逆操作就可以了
二、應用:
1.如果是簡單的http地址,如 http://www.w3school.com.cn/My first/?uname=張三&pwd=123456,使用encodeURI編碼就行,這樣瀏覽器拿到編碼(utf8)後的地址就能正常開啟頁面(現在大多數瀏覽器都會自動進行編碼,ie11還不行)
2.如果是比較複雜的http地址,如 http://www.w3school.com.cn/My first/?newUrl=http地址
需要通過url傳地址,然後跳轉到新的地址,那這個要傳遞的地址(http地址)需要使用encodeURIComponent進行編碼
三、參考連結: