Three methods of getting parameters in Url address

Keywords: Javascript Big Data

The code to get Url is as follows: window.location.href;

Method 1: native js (assuming the Url address has been obtained)

var url = 'https://gitbook.cn/gitchat/geekbooks?tag=JavaScript&name=pwwu&age=24';
        var temp1 = url.split('?');
        var pram = temp1[1];
        var keyValue = pram.split('&');
        var obj = {};
        for (var i = 0; i<keyValue.length; i++){
            var item = keyValue[i].split('=');
            var key = item[0];
            var value = item[1];
            obj[key] = value;
        }
        console.log(url);
        console.log(temp1);    //  ['https://gitbook.cn/gitchat/geekbooks','tag=JavaScript&name=pwwu&age=24']
        console.log(pram);     //  tag=JavaScript&name=pwwu&age=24
        console.log(keyValue); //  ['tag=JavaScript','name=pwwu','age=24']
        console.log(obj);      //  {tag:'JavaScript',name:'pwwu',age:'24'}

Summary: the main idea is to split the Url into different blocks with split(), and the return value is an array until it is ['tag=JavaScript ',' name=pwwu ',' age=24 '],
Then, each item in the array is passed into an empty object obj in the form of key value pairs (here, the array needs to be traversed). Finally, the corresponding parameters are obtained by obj.name "point".

Method 2: URLSearchParams() function (if you can't remember the function name, you can print it directly in the browser)
 

     var url2 = 'https://gitbook.cn/gitchat/geekbooks?tag=%E5%A4%A7%E6%95%B0%E6%8D%AE&name=gy&age=22';
        var temp2 = url2.split('?')[1];
        var pram2 = new URLSearchParams('?'+temp2);
        console.log(pram2.get('tag')); // Big data
        console.log(pram2.get('name'));// gy
        console.log(pram2.get('age')); // 22
        console.log(temp2);   //tag=%E5%A4%A7%E6%95%B0%E6%8D%AE&name=gy&age=22

Method 3 use regular expression

//Get the parameter method in url
        function getUrlParam(name) {
            //Constructing a regular expression object with target parameters
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
            //Match target parameters
            var r = window.location.search.substr(1).match(reg);
            //Return parameter
            if (r != null) {
                return unescape(r[2]);
            } else {
                return null;
            }
        }
        var ABC = getUrlParam();
        console.log(ABC);


This time, we will introduce the above three kinds for the time being, which will be supplemented in the future.

Posted by ironman32 on Sat, 02 Nov 2019 15:45:01 -0700