How to Get URL Parameters
Read this JavaScript tutorial and learn how you can easily get the URL parameters with the help of the methods provided by the URLSearchParams interface.
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 <kbd class="highlighted">URL</kbd> 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 <kbd class="highlighted">window.location.href</kbd>. Otherwise, you can use anything like “https://example.com/?product=trousers&color=black&newuser&size=s”.
javascript window location search
// 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.href);When you want to access the params of a URL instance like <kbd>myUrl</kbd>, you can use <kbd class="highlighted">myUrl.searchParams.get($PARAM_NAME)</kbd>, where $PARAM_NAME is the placeholder for the parameter's key. See the example below.
Javascript url search params get method
If you want to check if the given parameter exists or not, use: <kbd class="highlighted">urlParams.has()</kbd>:
Javascript url search params has method
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 <kbd class="highlighted">getAll()</kbd> method
javascript url search params getAll method