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"
复制代码
在实际使用中, decodeURI() 函数 和 encodeURI() 函数 用来操作完整的URI,使得关键字不会失效.而decodeURIComponent() 函数 和 encodeURIComponent() 函数则用来操作单个参数.