encodeURIComponent、decodeURIComponent、encodeURI的区别和使用

1. encodeURIComponent() 函数可把字符串作为 URI 组件进行编码。

encodeURIComponent('周圣楠') // "%E5%91%A8%E5%9C%A3%E6%A5%A0"

2. decodeURIComponent() 函数可对 encodeURIComponent() 函数编码的 URI 进行解码

decodeURIComponent('%E5%91%A8%E5%9C%A3%E6%A5%A0') // "周圣楠"

3. encodeURI() 作用和 encodeURIComponent() 类似,但他们编码的范围有区别:

3.1 encodeURI()方法不会对下列字符编码:ASCII字母、数字、~!@#$&*()=:/,;?+'
3.2 encodeURIComponent()方法不会对下列字符编码:ASCII字母、数字、~!*()'
3.3 二者都会对中文进行编码

一般来说,在编码范围内,encodeURI() 和 encodeURIComponent() 编码后的结果是一样:

encodeURI('周圣楠') // "%E5%91%A8%E5%9C%A3%E6%A5%A0"
encodeURIComponent('周圣楠') // "%E5%91%A8%E5%9C%A3%E6%A5%A0"
3.3 使用场景的区别:对 整个URL 进行编码就使用 encodeURI(),对 URL中的参数 或者 URL后面的一部分 进行编码就使用 encodeURIComponent()

使用 encodeURI() 只将空格编码成 20%

encodeURI('http://tieba.baidu.com/?name=zhou value') // "http://tieba.baidu.com/?name=zhou%20value"

使用 encodeURIComponent() 对整个 URL编码可能会导致URL失效(不仅编码了空格,还编码了 // ):

encodeURIComponent('http://tieba.baidu.com?name=zhou value') // "http%3A%2F%2Ftieba.baidu.com%3Fname%3Dzhou%20value"

因此一般情况下,如果我们只需对 URL 后面的参数进行编码的话,使用 encodeURIComponent() 编码参数后,再拼接到 URL 后面去

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容