當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
javascript中编码与解码的decodeURI()、decodeURIComponent()区别
生活随笔
收集整理的這篇文章主要介紹了
javascript中编码与解码的decodeURI()、decodeURIComponent()区别
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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#abcvar 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"
?
轉載于:https://www.cnblogs.com/Model-Zachary/p/11193556.html
總結
以上是生活随笔為你收集整理的javascript中编码与解码的decodeURI()、decodeURIComponent()区别的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: vue兼容ie10问题并且node——m
- 下一篇: 萌新自我介绍