javaScript encodeURL與encodeURLComponent區(qū)別

1. URL編碼方式

Global對象的encodeURL()和encodeURLComponent()方法可以對URL進行編碼。有效的URL中不能包含某些字符串,例如空格。他們用特殊的UTF-8編碼替換所有無效的字符,從而讓瀏覽器理解。
encodeURL()主要用于整個URL,而encodeURLComponent()主要用于對URL中的某一段。它們的區(qū)別在于,encodeURL()不會對本身屬性url的特殊字符進行編碼,例如“冒號、正斜杠、問號、井號”;而encodeURLComponent()則會對它發(fā)現(xiàn)的任何非標準字符進行編碼。
代碼:

let url = 'http://www.itdecent.cn/writer/notebooks/33382883/notes/40138710'
let encode = encodeURI(url) 
let encodeComponent = encodeURIComponent(url)
console.log(encode) // http://www.itdecent.cn/writer/notebooks/33382883/notes/40138710
console.log(encodeComponent) // https%3A%2F%2Fwww.itdecent.cn%2Fwriter%2Fnotebooks%2F33382883%2Fnotes%2F40138710

2. URL解碼方式

let decode = decodeURI(encode) // encode 對應上面的代碼
let decodeComponent = decodeURIComponent(encodeComponent)
console.log(decode) // http://www.itdecent.cn/writer/notebooks/33382883/notes/40138710
console.log(decodeComponent) // http://www.itdecent.cn/writer/notebooks/33382883/notes/40138710

總結(jié):
在實踐中encodeURLComponent()比encodeURL()更常用,因為常見的是查詢字符串參數(shù),而不是對url進行編碼。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容