Check the query parameter value in the current page URL

Time:2021-1-19

First, what are the query parameters in the page URL?
for examplehttp://segmentfault.com/x.html?a=0&b=1&c=2A, B, and C after the URL are query parameters

In the process of development, we will meet some requirements like this:

  1. Judge whether there is a parameter in the current link, and do corresponding processing according to different parameters.

  2. For example, the content in the same page is generated by the current user,
    Then, after sharing the current page, when other people see the page, some of the contents (buttons, text, etc.) need to be changed.

Therefore, we should have a method to obtain the parameter values in the current page URL. I have seen a very simple method like this:

function getQueryValue(key){
    var match=location.search.match(new RegExp(key+'=([^&]*)'));
    return match&&match[1]||'';
}

Analyze this method:

  • location.searchProperty is used to set or get the query string of the current URL (? Symbol and the following part)

  • http://segmentfault.com/x.html?a=0&b=1&c=2In this caselocation.searchmean?a=0&b=1&c=2

  • match()Method to retrieve a specified value within a string or find a match for one or more regular expressions.
    The method is similarindexOf()andlastIndexOf(), but it returns the specified value, not the position of the string.

  • new RegExp(key+'=([^&]*)')Here, the regular expression matches all the characters except & key

  • Finally, the function returns parameterskeyValue ofvalue.

PS: ifvalueEmpty or parameterkeyDoes not exist. All returned values are""
At this point, we can use this method to detect the parameter value of the URL in the page.

Recommended Today

Practice of query operation of database table (Experiment 3)

Following the previous two experiments, this experiment is to master the use of select statements for various query operations: single table query, multi table connection and query, nested query, set query, to consolidate the database query operation.Now follow Xiaobian to practice together!Based on the data table (student, course, SC, teacher, TC) created and inserted in […]