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進行編碼。