skip to content

JavaScript
URL 的编码

举个例子:拼接出一个网址,用 Google 搜索 Rock&Roll

方法一

const u1 = new URL('https://www.google.com/search')
u1.searchParams.set('q', 'Rock&Roll')
console.log(u1.toString()) // https://www.google.com/search?q=Rock%26Roll

方法二

const u2 = `https://www.google.com/search?q=${encodeURIComponent('Rock&Roll')}`
console.log(u2) // https://www.google.com/search?q=Rock%26Roll

错误的方法

const u3 = encodeURI(`https://www.google.com/search?q=Rock&Roll`)
console.log(u3) // https://www.google.com/search?q=Rock&Roll

; / ? : @ & = + $ , # 这些在 encodeURI() 中不被编码的符号,在 encodeURIComponent() 中会统统被编码,至于具体的编码方法,两者是一样

JavaScript.Info - 编码字符串

ruanyf - 关于 URL 编码