当URL的参数中出现诸如+,空格,/,?,%,#,&,=等特殊字符串符号时,因为上述字符有特殊含义,导致服务器端无法正确解析参数,如何处理?解决办法:将这些字符转化成服务器可以识别的字符。

一. encodeURI()

把字符串作为 URI整体进行编码,所以URI组件中的特殊分隔符号 (;/:@&=+$?#) (可以使用 encodeURIComponent() 方法分别对特殊含义的 ASCII 标点符号进行编码。),encodeURI() 函数不会进行转义。该方法不会对 ASCII 字母和数字进行编码,也不会对这些 ASCII 标点符号进行编码:- _ . ! ~ * ‘ ( ) 。

1
2
3
encodeURI('#') // '#'
encodeURI('_') // '_'

1
2
3
4
encodeURI('https://mp.weixin.qq.com/')
// 输出:'https://mp.weixin.qq.com/'
encodeURI('https://mp.weixin.qq.com/cgi-bin/appmsg?t=media/appmsg_edit_v2')
// 'https://mp.weixin.qq.com/cgi-bin/appmsg?t=media/appmsg_edit_v2'

二. encodeURIComponent()

把字符串作为 URI 组件的一部分(如path/query/fragment等)进行编码,所以用于分隔 URI 各个部分的特殊分隔符号(;/?:@&=+$,#)也会被转义。返回值中某些字符将被十六进制的转义序列替换。该方法也不会对 ASCII 字母和数字进行编码,也不会对这些 ASCII 标点符号进行编码:- _ . ! ~ * ‘ ( ) 。

1
2
encodeURIComponent(';') // '%3B'
encodeURIComponent('#') // '%23'
1
2
encodeURIComponent('https://mp.weixin.qq.com/cgi-bin/appmsg?t=media/appmsg_edit_v2')
// 'https%3A%2F%2Fmp.weixin.qq.com%2Fcgi-bin%2Fappmsg%3Ft%3Dmedia%2Fappmsg_edit_v2'

三. decodeURI()/decodeURIComponent()

decodeURI() 函数可对 encodeURI() 函数编码过的 URI 进行解码。
decodeURIComponent() 函数可对 encodeURIComponent() 函数编码的 URI 进行解码。

1
2
3
4
decodeURI('https://mp.weixin.qq.com/')
// 'https://mp.weixin.qq.com/'
decodeURI('https://mp.weixin.qq.com/cgi-bin/appmsg?t=media/appmsg_edit_v2')
// 'https%3A%2F%2Fmp.weixin.qq.com%2Fcgi-bin%2Fappmsg%3Ft%3Dmedia%2Fappmsg_edit_v2'
1
2
3
4
decodeURIComponent('%3B') // ';'
decodeURIComponent('%23') // '#'
encodeURIComponent('https%3A%2F%2Fmp.weixin.qq.com%2Fcgi-bin%2Fappmsg%3Ft%3Dmedia%2Fappmsg_edit_v2')
// https://mp.weixin.qq.com/cgi-bin/appmsg?t=media/appmsg_edit_v2

四. escape()

用于对字符串进行编码,并返回编码字符串。但目前已不推荐使用该函数对URI进行编码。(已经弃用)

1
2
3
4
decodeURI('https://mp.weixin.qq.com/')
// 'https://mp.weixin.qq.com/'
decodeURI('https://mp.weixin.qq.com/cgi-bin/appmsg?t=media/appmsg_edit_v2')
// 'https%3A%2F%2Fmp.weixin.qq.com%2Fcgi-bin%2Fappmsg%3Ft%3Dmedia%2Fappmsg_edit_v2'
1
2
3
4
decodeURIComponent('%3B') // ';'
decodeURIComponent('%23') // '#'
encodeURIComponent('https%3A%2F%2Fmp.weixin.qq.com%2Fcgi-bin%2Fappmsg%3Ft%3Dmedia%2Fappmsg_edit_v2')
// https://mp.weixin.qq.com/cgi-bin/appmsg?t=media/appmsg_edit_v2

问题思考

在项目中哪里会用到呢?
假如你要给后端传一个16进制 HEX值(#FFFFFF),那么你就会用到encodeURIComponent去转义。