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

1、encodeURIComponent 转义

除了字母、数字、(、)、.、!、~、*、'、-和_之外的所有字符(可看下表的非转义字符更清晰)。

注意:为了避免服务器收到不可预知的请求,对任何用户输入的作为URI部分的内容你都需要用encodeURIComponent进行转义。

var x = encodeURIComponent("https://baidu.com/a(-_.!~*')1");

console.log(x); // "https%3A%2F%2Fbaidu.com%2Fa(-_.!~*')1"

2、encodeURI 会替换所有的字符,

但不包括以下字符,即使它们具有适当的UTF-8转义序列:

注意:encodeURI 自身无法产生能适用于HTTP GET 或 POST 请求的URI,

例如对于 XMLHTTPRequests, 因为 "&", "+", 和 "=" 不会被编码,然而在 GET 和 POST 请求中它们是特殊字符。

故因采用encodeURIComponent这个方法会对这些字符编码。

var y = encodeURI("https://www.baidu.com/;,/?:@&=+$a2-_.!~*'()#");

console.log(y); //"https://www.baidu.com/;,/?:@&=+$a2-_.!~*'()#"

3、decodeURIComponent 可对 encodeURIComponen编码的 URI 进行解码。

var m = decodeURIComponent("https%3A%2F%2Fbaidu.com%2Fa(-_.!~*')1");

console.log(m); // "https://baidu.com/a(-_.!~*')1"

4、decodeURI 可对 encodeURI编码的 URI 进行解码。

var n = decodeURI("%E4%B8%AD%E5%9B%BDhttps://www.baidu.com/;,/?:@&=+$a2-_.!~*'()#");
    
console.log(n); //"中国https://www.baidu.com/;,/?:@&=+$a2-_.!~*'()#"

5、运用:取地址栏中文参数乱码

send.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
        <title>send</title>
    </head>
    <body>
    </body>
    <script type="text/javascript" charset="utf-8">
        //window.location.href = 'reception.html?p=广东&c=广州'
        window.location.href = 'reception.html?p=%E5%B9%BF%E4%B8%9C&c=%E5%B9%BF%E5%B7%9E'
    </script>
</html>

reception.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
        <title>reception</title>
    </head>
    <body>

    </body>
    <script type="text/javascript" charset="utf-8">
        /*
         * 取地址栏的参数
         * @param key
         * key为传递的参数名称 例如 reception.html?p=广东&c=广州,key就是p和c
         * @returns
         */
        function getUrlParam(key) {
            // 获取参数
            var url = window.location.search;
            //window.search 取到的是一串带参数的字符串,如:?p=广东&c=广州

            // 正则筛选地址栏
            var reg = new RegExp("(^|&)" + key + "=([^&]*)(&|$)");
            // 匹配目标参数
            var result = url.substr(1).match(reg);
            //返回参数值
            return result ? decodeURIComponent(result[2]) : null;
        }
        // 控制台打印参数 p
        console.log(getUrlParam('p')); // 结果为 广东
        // 控制台打印参数 c
        console.log(getUrlParam('c')); // 结果为 广州
    </script>
</html>
一辈子很短,努力的做好两件事就好;第一件事是热爱生活,好好的去爱身边的人;第二件事是努力学习,在工作中取得不一样的成绩,实现自己的价值,而不是仅仅为了赚钱。
原文地址:https://www.cnblogs.com/antao/p/12974228.html