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;//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;//"http://www.baidu.com?code=20180711%23abc"
http://www.xxx.com接收參數
location.search //"?code=20180711%23abc"
decodeURIComponent("?code=20180711%23abc") //"?code=20180711#abc"
這樣子看來參數是不是正確了呢?
————————————————
版權聲明:本文爲CSDN博主「格子丿」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/qq_39712029/article/details/81003518