Get Query String Values from Current URL in JavaScript

Last updated on March 7, 2023

To get query string values from the URL you need to use the URL interface that provides properties to read and modify the URL components. In this article, we will get query string values by using URL interface’s searchParams property.

To begin with, we need to get the current web page URL which can be obtained through the document interface property. Look at the below,

// Output:

Next, create an object of the URL interface and pass the absolute URL of the current web page to the constructor. As we know that document.location returns the current page URL.

let url = (new URL(document.location));

Once the object is created, we can access the searchParams property through dot notation.

let parameters = url.searchParams;

Above we accessed the searchParams property and assigned it to the new variable parameters, which can fetch all the values from the query string through the get() method. So in the above URL, we have two key-values-based parameters, to get them we need to use the get() method.

Let’s get the parameter id value from the URL. To that we need to pass the id key as a string into the get() method.

let id = parameters.get("id");
// Output: 20

Similarly, to get the profession value we need to pass the key in the get() method.

let profession= parameters.get("profession");
// Output: doctor

Written by
I am a skilled full-stack developer with extensive experience in creating and deploying large and small-scale applications. My expertise spans front-end and back-end technologies, along with database management and server-side programming.

Share on:

Related Posts

Tags: JavaScript,