How To Get URL Parameters Using JavaScript
JavaScript
06/05/2021
First of all, it's important to distinguish between:
- Query parameters: Key value pairs that follow a
?
or&
(e.g.?key=value
), and - Path parameters: Commonly known as slugs or permalinks (e.g.
/param1/param2
)
Query parameters
For query parameters, JavaScript offers a built-in interface called URLSearchParams
that allows you to easily retrieve them. One initializes the interface by passing a string of the parameters to it.
As an example, let's assume we have the following link which filters through blog posts: https://dilshankelsen.com/blog/posts?year=2021&category=javascript
.
const queryString = window.location.searchconsole.log(queryString) // '?year=2021&category=javascript'
const urlParams = new URLSearchParams(queryString)
As you see, we use the built-in property from the window object to extract all query parameters as a string, which we then use to instantiate a new URLSearchParams
object. To then retrieve the values for each parameter is as easy as:
const category = urlParams.get('category')console.log(category) // 'javascript'
Path parameters
While there isn't any fancy interface that allows the same degree of simplicity for path parameters, retrieving them is still relatively easy. Similarly to before, we first extract the path parameters as whole.
const pathString = window.location.pathnameconsole.log(pathString) // '/blog/posts'
Next, we split up the whole path using /
as a reference. Remember to filter
any empty strings that result from the split
output.
const pathParams = pathString.split('/').filter(param => param.length > 0)console.log(pathParams) // Array [ "blog", "posts" ]
Then, it's as simple as selecting the desired parameter from the array using an index.