js编码解码decodeURI()与decodeURIComponent()的区别

原文链接:https://blog.csdn.net/qq_39712029/article/details/81003518

  1. 定义和用法
    decodeURI() 函数可对 encodeURI() 函数编码过的 URI 进行解码。

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

    从W3C的定义和用法来看,两者没有什么区别,但是两者的参数是有区别的:

decodeURI(URIstring) //URIstring 一个字符串,含有要解码的 URI 或其他要解码的文本。

decodeURIComponent(URIstring) //URIstring 一个字符串,含有编码 URI 组件或其他要解码的文本。

2.使用中区别用法
区别:encodeURIComponent和decodeURIComponent可以编码和解码URI特殊字符(如#,/,¥等),而decodeURI则不能。

encodeURIComponent('#')
"%23"
decodeURI('%23')
"%23"
decodeURIComponent('%23')
"#"
encodeURI('#')
"#"

可以看出encodeURI和decodeURI对URI的特殊字符是没有编码和解码能力的,实际项目中我们一般需要get请求的方式在地址栏中拼接一些参数,但是参数中如果出现#,/,&这些字符,就必须要用decodeURIComponent了,不然这些特殊字符会导致我们接收参数的错误

假如我们要传一个code字段到http://www.xxx.com,值为20180711#abc

var codeVal = encodeURI('20180711#abc');
var url = 'http://www.xxx.com?code=' + codeVal;
console.log(url);
http://www.xxx.com?code=20180711#abc

http://www.xxx.com接收参数

  location.search  //"?code=20180711";

decodeURI("?code=20180711")  //"?code=20180711"

这时候我们拿到的code参数明显是错误的,被特殊字符#截断了,下面我们来看用decodeURIComponent方法:

var codeVal = encodeURIComponent('20180711#abc');
var url = 'http://www.baidu.com?code=' + codeVal;
url;
"http://www.baidu.com?code=20180711%23abc"

http://www.xxx.com接收参数

location.search  //"?code=20180711%23abc"
decodeURIComponent("?code=20180711%23abc")  //"?code=20180711#abc"

  • 3
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值