简体   繁体   中英

Can anybody explain to me step by step how is this code able to get parameters from website URL?

I was trying to get some parameters from url.

As usual I was searching online how, and here's the useful link I found.

https://html-online.com/articles/get-url-parameters-javascript/

Below is the code I got from this website:

function getUrlVars() {
    var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
        vars[key] = value;
    });
    return vars;
}

This code works very well. It does what I wanted to do. But I'm not quite sure why.

Does this mean that the references \\1, \\2 goes into the function's parameter respectively?

If that's the case, what is this first parameter m for?

Can anybody explain to me step by step what's happening behind this code please?

The second argument to .replace can be a function. If the function is provided, then its arguments are (first) the full string that was matched, followed by capture groups. For example, if there's one capture group, the string captured by the first group will be the second argument; if there are two capture groups, the string captured by the second group will be the third argument, and so on.

If that's the case, what is this first parameter m for?

That's the full match, which is not used - but there's no way to use later arguments (past the first) without also declaring a variable name for the first argument, so in order to use the capture groups, the argument for the full match also has to be declared, even if it goes unused.

Here, the value in key will be the substring matched by the capture group

([^=&]+) (a key in the query string - one or more characters other than = and & )

and the value in value will be the substring matched by the capture group

([^&]*) (the associated value for the query string - zero or more characters other than & )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM