原生js中编码的三种方法
在开发中经常需要对用户输入的数据进行编码然后才能通过HTTP请求发送给后台,或者对传递过来的数据进行解码。在JS中原生提供了三种编码/解码方式,分别是 encodeURI
、 encodeURIComponent
和 escape
。
encodeURI
该方法不会对ASCII表中的字母和数字编码,同时也不会对ASCII中的标点符号编码 **-_.~*’()**
在URI中具有特殊含义的符号 **;/?:@&=+$,#**
同样不会被编码。
1 | let url = 'https://google.com/pathname?a=1&b=abcde&c=黄山#hash'; |
encodeURIComponent
该方法相比encodeURI
多编码URI中具有特殊含义的符号 **;/?:@&=+$,#**
1 | let url = 'https://google.com/pathname?a=1&b=abcde&c=黄山#hash'; |
escape(不推荐使用,推荐使用上面两个方法代替)
该方法会对ASCII中 *字母、数字及符号@-_+./**之外的所有字符进行编码。
1 | let url = 'https://google.com/pathname?a=1&b=abcde&c=黄山#hash'; |
解码
三种编码方法对应的解码方法分别是:
编码 | 解码 |
---|---|
encodeURI | decodeURI |
encodeURIComponent | decodeURIComponent |
escape | unescape |
1 | let res = encodeURI("黄山"); // %E9%BB%84%E5%B1%B1 |