Skip to main content Accessibility Feedback

getParams.js

Get all URL parameters from a query string.

Source Code

Example

let url = 'https://gomakethings.com?sandwhich=chicken%20salad&bread=wheat&topping=tomato&topping=spicy+mayo';
let params = getParams(url);

The helper function

/**
 * Get the URL parameters
 * (c) Chris Ferdinandi, MIT License, https://gomakethings.com
 * @param  {String} url The URL
 * @return {Object}     The URL parameters
 */
function getParams (url = window.location) {
	let params = {};
	new URL(url).searchParams.forEach(function (val, key) {
		if (params[key] !== undefined) {
			if (!Array.isArray(params[key])) {
				params[key] = [params[key]];
			}
			params[key].push(val);
		} else {
			params[key] = val;
		}
	});
	return params;
}

How it works

Learn more about the URL and URLSearchParams APIs.