Using JS to get parameters on url

function getQuery(key) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"),
        r = window.location.search.substr(1).match(reg);
    if (r != null) return decodeURI(r[2])
    return null
}

this code is an encapsulated function to get the parameters on URL. It uses regular matching, but my regular is relatively weak. Trouble the big gods in the community to help me interpret

.

(^ | &): what does it mean

= ([^ &] *) (& | $) what does it mean

Mar.07,2021

your program doesn't work properly, the parameter key is not used, and the variable name comes from somewhere.
estimates that the correct code is

function getQuery(keyName) {
    var reg = new RegExp("(^|&)" + keyName+ "=([^&]*)(&|$)"),
        r = window.location.search.substr(1).match(reg);
    if (r != null) return decodeURI(r[2])
    return null
}
The function of

is to query the value of keyName in URI.
after match matching, the returned array structure is
[the value of the whole match, header or &, keyName (that is, the value of the following valid part), the position of the tail or &, index: match, the whole input of input:]


Modern browsers can use:

// var url_string = "http://www.example.com/t.html?a=1&b=3&c=m2-m3-m4-m5";

var url = new URL(window.location.href);
var c = url.searchParams.get("c");

Reference:
https://developer.mozilla.org.
from-the-get-parameters?page=1&tab=votes-sharptab-top" rel= "nofollow noreferrer" > https://stackoverflow.com/que.


(^|&)&
=([^&]*)(&|$)'='+'&''&'

add upstairs:

str.match (regexp);

if the string matches the expression, an array is returned, the first item of the array is to match the complete string, and the subsequent item is the result captured in parentheses. If there is no match, return null

ask again and again:
ide/Regular_Expressions" rel=" nofollow noreferrer "> regular expression

online regularization tool

Menu