Get parameters in url path

 

Introduction

When using js, we may sometimes have the need to obtain a parameter specified by the browser address bar, such as: https://i.cnblogs.com/EditPosts.aspx?postid=8628413&update=1 ,

If you want to get the content of postid 8628413 , or the content of update 1 , then the solution is provided below.

Solution

In fact, the solution is quite simple, as long as it can be dealt with through a function

 

        //Current url address bar file:///C:/Users/admin/Desktop/test.html?id=2
        function GetQueryString(name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
            console.log(window.location.search)//?id=2
            var r = window.location.search.substr(1).match(reg);
            if (r != null) return unescape(r[2]);
            return null;
        }
        console.log(GetQueryString('id'))//2    

The usage of the above function is very simple, just pass in the url parameter you want to get the return value, note that the parameter is a string

divergent thinking

The above function directly solves the problem of getting the parameters in the url of the current page. If something happens, we may not want to process the url, but want to get the parameters in a specific string, such as: postid=8628413&update=1

Then you want to get the corresponding value of the postid so how do you do it?

Just need to understand the principle of the above function, it is easy to rewrite

 

        function GetQueryString(str,name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");     
            //str = postid=8628413&update=1                   
            //其实str 就相当于 window.location.search.substr(1)
            var r = str.match(reg);
            if (r != null) return unescape(r[2]);
            return null;
        }
        console.log(GetQueryString('postid=8628413&update=1','postid'))

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324802844&siteId=291194637