zl程序教程

您现在的位置是:首页 >  其他

当前栏目

小程序URL解码decodeURI与decodeURIComponent的区别

程序 区别 url 解码
2023-09-11 14:14:25 时间
  • 定义

    decodeURI() 函数可对 encodeURI() 函数编码过的 URI 进行解码。

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

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

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

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

encodeURIComponent和decodeURIComponent可以编码和解码URI特殊字符(如#,/,¥等),而decodeURI则不能。

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

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

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

let url = 'http://www.baidu.com?code=123#abc哈哈'
console.log(encodeURI(url))
//http://www.baidu.com?code=123#abc%E5%93%88%E5%93%88

console.log(encodeURIComponent(url))
//http%3A%2F%2Fwww.baidu.com%3Fcode%3D123%23abc%E5%93%88%E5%93%88