How to Get URL Parameters with Javascript

In modern browsers getting url parameters has become quite simple with the new URL and URLSearchParams objects. Prior to this, to get parameters of a url required regular expressions or splitting strings, which was mostly a pain.

The URL and URLSearchParams Objects

A URL object basically represents a url. The search property of the URL object returns the string of query parameters.

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

var query_string = url.search;

// will output : ?id=100&topic=main
console.log(query_string);

The query parameters string can be used to create a URLSearchParams object, through which you can get parameter values.

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

var query_string = url.search;

var search_params = new URLSearchParams(query_string); 

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

// output : 100
console.log(id);

Getting All URL Parameters

The URLSearchParams object basically is list of parameter names and values. You can iterate it to get all parameters with their values.

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

var search_params = new URLSearchParams(url.search); 

// iterate over the query parameters
for(var i of search_params) {
	// i an an array
	// i[0] => name 
	// i[1] => value
	console.log(i[0] + ' : ' + i[1]);
}

Note that it is a for .. of loop rather than a for .. in loop.

Checking Whether a 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.

If the parameter exists, its value can be found through the get method.

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

var search_params = new URLSearchParams(url.search); 

// this will be true
if(search_params.has('id')) {
	var id = search_params.get('id');

	// output : 100
	console.log(id)
}

In case the url parameter is multi-valued, the getAll method can be used. It returns an array of values.

var url = new URL('http://demo.com?tags=one&tags=two&tags=three&topic=main');

var search_params = new URLSearchParams(url.search); 

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

// output : Array [ "one", "two", "three" ]
console.log(tags);

Using the Current URL ?

The document.URL property gives the current url in the browser window. You can use that to get its parameters.

How to Change URL Parameters with Javascript