Read URL query string parameters in Javascript
July 04, 2020
#Javascript
You have an url like this https://example.com/path/to/page?name=Luke&color=purple
and you want to easily access the value of name
and color
maybe because you’re going to do different stuffs based on query string parameters.
It’s time to use URL Search Params !
UrlSearchParams
The URLSearchParams interface give us some methods to manipulate the query string of a given URL.
If you would like to check if a param is defined inside the url and then read its value, you can use has
and get
method.
Let’s see a quick example:
// (the url in our example will be https://example.com/path/to/page?name=Luke&color=purple)
// read the url query string through the window.location object
const queryString = window.location.search;
console.log(queryString); // '?name=Luke&color=purple'
const urlParams = new URLSearchParams(queryString);
urlParams.has("name") === true; // true
urlParams.has("color") === true; // true
urlParams.get("name") === "Luke"; // true
urlParams.get("color") === "purple"; // true
Please note: you don’t have to worry about the initial ?
.
The constructor of URLSearchParams will skip it, if present.
Browser compatibility ⚠️
UrlSearchParams is not supported yet from Internet Explorer, while it has fully support from all the other browsers: Chrome, Safari, Firefox, Edge and Opera.
For further details check the official URLSearchParams documentation where you can find all the methods to work with URL query string parameters.
Hope you enjoy this post,
Pingu 🐧