js encodeURI 和 encodeURIComponent 的区别

一、共同点

  1. 把字符串作为 URI 进行编码

  2. 方法不会对 ASCII 字母和数字进行编码,也不会对这些 ASCII 标点符号进行编码: - _ . ! ~ * ' ( ) 。

二、区别

1.encodeURI(URIstring): 

  对在 URI 中具有特殊含义的 ASCII 标点符号,不会进行转义的:;/?:@&=+$,#

console.log(encodeURI("http://www.baidu.com.cn"));//http://www.baidu.com.cn
console.log(encodeURI("http://www.baidu.com.cn/p 1/"));//http://www.baidu.com.cn/p%201/
console.log(encodeURI(",/?:@&=+$#"));//,/?:@&=+$#

2.encodeURIComponent(URIstring)

  对在 URI 中具有特殊含义的 ASCII 标点符号,也会进行转义的:;/?:@&=+$,#

console.log(encodeURIComponent("http://www.baidu.com.cn"));//http%3A%2F%2Fwww.baidu.com.cn
console.log(encodeURIComponent("http://www.baidu.com.cn/p 1/"));//http%3A%2F%2Fwww.baidu.com.cn%2Fp%201%2F
console.log(encodeURIComponent(",/?:@&=+$#"));//%2C%2F%3F%3A%40%26%3D%2B%24%23

三、解决url传递解析不正确的问题

  1. 中文

  2. 参数比较复杂

  var req=encodeURIComponent(`{"query":{"discoverId":${this.curDiscoverId}},"page":{"pageSize":20,"pageNo":${curPage}}}`);
原文地址:https://www.cnblogs.com/yuesu/p/9561835.html