How to Get URL Parameters

URL parameters or query string parameters are used to send a piece of data from client to server via a URL. They can contain information such as search queries, link referrals, user preferences, etc.

JavaScript has a default class URL used to handle everything about URLs, including the parameters.

You can make a URL instance from any URL string you wish. If you want to access the URL of the current web page a user is browsing, you can use window.location.toLocaleString(). Otherwise, you can use anything like “https://example.com/?product=trousers&color=black&newuser&size=s”.

// using a custom URL string
const myUrl1 = new URL("https://example.com/?product=trousers&color=black&newuser&size=s");

// using the current page's URL
const myUrl2 = new URL(window.location.toLocaleString());

When you want to access the params of a URL instance like myUrl, you can use myUrl.searchParams.get($PARAM_NAME). See the example below.

Javascript url search params get method
const urlParams = new URL("https://example.com/?product=trousers&color=black&newuser&size=s").searchParams; const product = urlParams.get('product'); console.log(product); // product const color = urlParams.get('color') console.log(color); // black const newUser = urlParams.get('newuser') console.log(newUser); // empty string const size = urlParams.get('size'); console.log(size); // s

If you want to check if the given parameter exists or not, use: urlParams.has():

Javascript url search params has method
const urlParams = new URLSearchParams("https://example.com/?product=trousers&color=black&newuser&size=s"); console.log(urlParams.has('size')); // true console.log(urlParams.has('paymentmethod')); // false

Multiple query values

There are times where multiple values are set for a specific parameter. This situation is common when the client wants to send an array. As the arrays are not directly supported in query parameters, the only way is to set multiple values for a single parameter name, like "https://example.com/?products=trousers&products=shirts". To access all the values set for a specific query name, we use the getAll() method

javascript url search params getAll method
const urlParams1 = new URL("https://example.com/?product=trousers&color=black&newuser&size=s").searchParams; console.log(urlParams1.getAll('color')); // [ 'black' ] const urlParams2 = new URL("https://example.com/?products=trousers&products=shirts").searchParams; console.log(urlParams2.getAll('products')); // [ 'trousers', 'shirts' ]