get query string value from url

get query string value from url
In this article, we are going to see, how to get the current page query string value from a URL with a particular param/key name.
for e.g : www.xyz.com?a=1&b=2....GetQueryStringValue('a') give value  = 1

function GetQueryStringValue(key) {
    key = key.replace(/[*+?^$.\[\]{}()|\\\/]/g, "\\$&"); // for escape RegEx meta chars
    let match = location.search.match(new RegExp("[?&]" + key + "=([^&]+)(&|$)"));
    return match && decodeURIComponent(match[1].replace(/\+/g, " "));
}

or :

To access the value of the query inside the browser, using JavaScript, we have a special API called URLSearchParam, supported by all modern browsers.

for e.g :
let params = new URLSearchParams(window.location.search)
params.get('a')

Post a Comment

0 Comments