js编码解码decodeURI()与decodeURIComponent()的区别 您所在的位置:网站首页 js是什么编码 js编码解码decodeURI()与decodeURIComponent()的区别

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

2024-07-03 04:42| 来源: 网络整理| 查看: 265

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"

这样子看来参数是不是正确了呢?



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有