js对url进行编码解码(三种方式)
    		       		warning:
    		            这篇文章距离上次修改已过450天,其中的内容可能已经有所变动。
    		        
        		                
                在JavaScript中,可以使用encodeURI,encodeURIComponent和decodeURI,decodeURIComponent函数来对URL进行编码和解码。
- encodeURI():用于编码整个URI。它不会对特定的字符进行编码:字母、数字、- ( )、- *、- -、- .、- _、- ~。
- encodeURIComponent():用于编码URI组件。它会对以下特定的字符进行编码:非字母数字字符、- :、- /、- ?、- #和- [、- ]、- @。
- decodeURI():用于解码由- encodeURI()编码的URI。
- decodeURIComponent():用于解码由- encodeURIComponent()编码的URI组件。
示例代码:
// 原始URL
let originalURL = "https://www.example.com/?query=Hello World!#Section";
 
// 编码URL
let encodedURL = encodeURI(originalURL);
console.log(encodedURL); // 输出: https://www.example.com/?query=Hello%20World!#Section
 
let encodedURLComponent = encodeURIComponent(originalURL);
console.log(encodedURLComponent); // 输出: https%3A%2F%2Fwww.example.com%2F%3Fquery%3DHello%20World%21%23Section
 
// 解码URL
let decodedURL = decodeURI(encodedURL);
console.log(decodedURL); // 输出: https://www.example.com/?query=Hello World!#Section
 
let decodedURLComponent = decodeURIComponent(encodedURLComponent);
console.log(decodedURLComponent); // 输出: https://www.example.com/?query=Hello World!#Section
评论已关闭