How to Get URL Query Parameters with Javascript

Published on June 11, 2018

URL search parameters can be read in Javascript using the URL and URLSearchParams objects.

Get URL Parameter Value By Name

Value of a given parameter name can be read through the get() method of URLSearchParams object.

var url = new URL('http://demo.com?id=100&topic=main');

// get access to URLSearchParams object
var search_params = url.searchParams; 

var id = search_params.get('id');
var topic = search_params.get('topic');

// "100"
console.log(id);

// "main"
console.log(topic);

Get All Values of Multi-Valued Parameter

In case the parameter is multi-valued, its values can be read through the getAll() method. This returns an array.

var url = new URL('http://demo.com?id=100&cat=js&cat=ui&cat=css');
var search_params = url.searchParams; 

var cat = search_params.getAll('cat');

// ["js", "ui", "css"]
console.log(cat);

Get All URL Parameters

All parameters in the URL can be looped using the forEach() method of URLSearchParams object.

var url = new URL('http://demo.com?id=100&cat=js&cat=ui&cat=css');
var search_params = url.searchParams; 

search_params.forEach(function(value, key) {
	console.log(key + '=' + value);
});

// "id=100"
// "topic=main"

Check If Parameter Exists in URL

The has() method can be used to check whether the parameter is contained in the url. It returns true if the parameter exists, otherwise it returns a false.

var url = new URL('http://demo.com?id=100&topic=main');
var search_params = url.searchParams; 

// true
if(search_params.has('id')) {
	// "100"
	console.log(search_params.get('id'))
}

Getting Parameters of Current Page URL

The document.URL property gives the current url of the browser window. Parameters in the url can then be read in the same way as described above.

var url = new URL(document.URL);
var search_params = url.searchParams;

// read url parameters now
How to Change URL Query Parameters with Javascript
Reading a URL and its Parts with Javascript
Loading Comments