如果你把一个URL作为GET请求的一部分来发送,你可能需要对它进行编码,例如。
你如何在JavaScript中对URL进行编码?
根据你需要做什么,有两个JavaScript函数可以帮助你。
第一个是encodeURI() ,第二个是encodeURIComponent() 。
注意:你可能会读到
escape(),但那已经过时了,不应该再使用。
这两个方法的不同之处在于它们对哪些字符进行了编码。
详细来说,encodeURI() 不编码~!@#$&*()=:/,;?+ ,encodeURIComponent() 不编码-_.!~*'() ,编码所有其他字符。为什么它们不同呢?因为它们的用途不同。
encodeURI()是指对一个完整的URL进行编码encodeURIComponent()是指对一个单一的URL参数值进行编码
如果你要在一个完整的URL上调用encodeURIComponent() ,因为它确实编码了/ ,URL路径分隔符也会被编码(除其他外)。
encodeURI("http://flaviocopes.com/ hey!/")
//"http://flaviocopes.com/%20hey!/"
encodeURIComponent("http://www.example.org/a file with spaces.html")
// "http%3A%2F%2Fflaviocopes.com%2F%20hey!%2F"
MDN提出了一项改进,以遵守RFC3986标准(http://tools.ietf.org/html/rfc3986),实现了以下功能。
const fixedEncodeURIComponent = (str) => {
return encodeURIComponent(str).replace(/[!'()*]/g, (c) => {
return '%' + c.charCodeAt(0).toString(16)
})
}
你为你将添加到URL中的每一个参数调用它。
encodeURI() 和encodeURIComponent() 方法有一个相应的decodeURI() 和decodeURIComponent() ,它做相反的工作,如果你使用Node.js,你可以在后端使用。