Get URL Parameters with JavaScript

date
May 30, 2021
slug
get-url-params-in-js
status
Published
summary
A common task, with a simple solution
tags
Coding
type
Post
Write a function, parse the url query string into an object.
Input: https://example.com/?product=shirt&color=blue&newuser&size=m
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 = {}
	urlArr.forEach(item=>{
		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 = 'https://example.com/?product=shirt&color=blue&newuser&size=m'
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:
URL {
  href: 'https://example.com/?product=shirt&color=blue&newuser&size=m',
  origin: 'https://example.com',
  protocol: 'https:',
  username: '',
  password: '',
  host: 'example.com',
  hostname: 'example.com',
  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 url.search 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
newuser
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 window.location.search to retrieve full url and "search" part.
Compatibility: https://caniuse.com/?search=urlsearchparams, basically it supports all major browsers except IE.
Ref:
 

© Craig Hart 2015 - 2021