DEV Community

Cover image for Get the values from the "GET" parameters of URL Using JavaScript
Sh Raj
Sh Raj

Posted on • Updated on

Get the values from the "GET" parameters of URL Using JavaScript

If you want to Use JavaScript by Default feature
Visit MDN :- https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams


let url = new URLSearchParams(location.href);//Let Window URL :- https://createevminutes.sh20raj.repl.co/shorts/#?collection=ryQCmre&id=1
url.get('id'); // 1
Enter fullscreen mode Exit fullscreen mode

Like we have URL http://www.example.com/t.html?a=1&b=3&c=m
and we want to get the value assigned to a i.e. 1 then when we will call getParameterByName('a') that will return 1

function getParameterByName(name, url = window.location.href) {
    name = name.replace(/[\[\]]/g, '\\$&');
    var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, ' '));
}
Enter fullscreen mode Exit fullscreen mode

Alternative Inbuilt JavaScript Function

var url_string = "http://www.example.com/t.html?a=1&b=3&c=m2-m3-m4-m5"; //window.location.href
var url = new URL(url_string);
var c = url.searchParams.get("c");
console.log(c);
Enter fullscreen mode Exit fullscreen mode

or

function getparam(param,url){
if(!url) url = window.location.href;
let urlParams = new URL(url);
return urlParams.searchParams.get(param);
}
Enter fullscreen mode Exit fullscreen mode

Minified and Fastest Version of the Function

function getparam(a,e){return e||(e=window.location.href),new URL(e).searchParams.get(a)}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)