js+jquery get URL get parameter tutorial

train of thought

Front-end development does not have a method to directly obtain URL parameters like the back-end, such as $_GET.

1

<?php echo $_GET["hu6cc"]; ?>

It is more complicated to obtain url parameters at the front end, and js+ regular expressions are needed to read and separate URLs to achieve the method of obtaining parameters.

Get URL parameter method

This is a complete js method to get url parameters

1

2

3

4

5

6

   //获取url中的参数

    function getUrlParam(name) {

        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象

        var r = window.location.search.substr(1).match(reg);  //匹配目标参数

        if (r != nullreturn unescape(r[2]); return null//返回参数值

    }

You can get the value of the parameter by passing the parameter name in the url through this function, for example:

1

http://www.che0.com/?url=hu6.cc

We want to get the value of reurl, we can write like this:

1

var url = getUrlParam('url');

The following is a method of obtaining url parameters written in the jquery library, which is simpler and clearer than native JS.

1

2

3

4

5

6

7

            (function ($) {

                $.getUrlParam = function (name) {

                    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");

                    var r = window.location.search.substr(1).match(reg);

                    if (r != nullreturn unescape(r[2]); return null;

                }

            })(jQuery);

After extending this method for jQuery, we can get the value of a parameter by the following method:

1

var url = getUrlParam('url');

Both methods can be copied and used directly, and the jquery method needs to refer to the jquery library.

Guess you like

Origin blog.csdn.net/winkexin/article/details/131017218