Get URL Parameters with JavaScript

May 30, 2021
A common task, with a simple solution
Write a function, parse the url query string into an object.
Output: { product: 'shirt', color: 'blue', newuser: '', size: 'm' }

Initially I was thinking about plain old method, by split the url into an array, then parse the each array item like this:
const parseQueryString = url => {
	const rawUrl = url.slice(url.indexOf('?') + 1)
	const urlArr = rawUrl.split('&')
	const obj = {}
		const key = item.split('=')[0]
		const val = item.split('=')[1] || ''
		obj[key] = val
	return obj	
Later, after search on the web, I found that I could use URL.searchParams() to extract the url parameters.
So let me dig into it, what's the URL() contains?
const urlForTesting = ''
const url = new URL(urlForTesting)
If you don't pass the actual url for testing, it will throw an error. Now print out the url:
  href: '',
  origin: '',
  protocol: 'https:',
  username: '',
  password: '',
  host: '',
  hostname: '',
  port: '',
  pathname: '/',
  search: '?product=shirt&color=blue&newuser&size=m',
  searchParams: URLSearchParams { 'product' => 'shirt', 'color' => 'blue', 'newuser' => '', 'size' => 'm' },
  hash: ''
So first we can see that seems like pretty useful, at least we don't need to do the old splice trick (url.slice(url.indexOf('?') + 1)), but what is searchParams?
According to MDN, we can see it's an URLSearchParams() object. when construct an URLSearchParams Object, kind reminds me of Set object, and we can print out like this:
for (const [key, val] of url.searchParams){
	console.log(key, val)
product shirt
color blue
size m
Note for (const [key, value] of url.searchParams) {} is same as:
for (const [key, value] of url.searchParams.entries()) {}
In our case, we can construct an url parameter object easily by using Object.fromEntries(), so here's the final result.
const parseQueryString = url => {
	const urlObj = new URL(url)
	const obj = Object.fromEntries(urlObj.searchParams)
	return obj
When we only have the search part, we can use const params = new URLSearchParams(url) instead. Also don't forget we can use window.location.href and to retrieve full url and "search" part.
Compatibility:, basically it supports all major browsers except IE.

© Craig Hart 2015 - 2021