A regular problem

[?&]key(=([^&-sharp]*)|&|-sharp|$)

this paragraph matches the regularity of the url query parameters, and what does the following | & |-sharp | $ mean? I can get rid of it and match successfully

Source

  function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&-sharp]*)|&|-sharp|$)"),
      results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return "";
    return decodeURIComponent(results[2].replace(/\+/g, " "));
  }
Apr.07,2021

The

tag selects so many. I don't know what language you use.

I say that in JavaScript , the regular | refers to or.
means | & |-sharp | $ means that the match ends with & or -sharp (where $ ends).

recommend a URL ide/design

this is more experiential.
may have some & -sharp that ends with a different URL .


key (= ([^ &-sharp] *)) can match key=1 but not key=-sharp123. Will mistakenly regard-sharp123 as the value of key

key (= ([^ &-sharp] *) | & |-sharp | $) can handle the above situation.


is very simple. According to the structure of URL, key in the query string, except for the protocol, user, password, host address and port before URL, there are still query strings and fragments.

The format of the

query string begins with the ? flag, and multiple query strings are concatenated with & . After querying the string, there may be a fragment part, whose structure is -sharpxxx .

explain this regular expression as follows: [? &] key (= ([^ &-sharp] *) | & |-sharp | $)

for URL https://cn.bing.com/search?q=url&qs=n

first judge the content before key . key may be the first query string Q , corresponding to q=url , then the beginning of the query string is preceded by ? ; if key is not the first query string, it is qs , corresponding to qs=n , then it must be preceded by the connector of the query string & .

and after the matching value of key , if there is a connection string, such as key is Q , then it is followed by & ; if it has reached the end of URL, then it is followed by the string ending delimiter $. There is another possibility that the URL also contains fragment parts, such as https://cn.bing.com/search?q=url&qs=n-sharpname1, so when key is qs , it is followed by -sharp .

so, in this regular expression, [?] represents key . In the part of the value corresponding to key , the characters that can never appear are & and -sharp , so use [^ &-sharp] to match & and . & |-sharp | $ indicates what may occur after the value corresponding to key .

also note that ([^ &-sharp] *) is also within the scope of | , indicating that the specified value is optional, so that you can match a special URL, such as URL, to get a null value for key .

Menu