How to Get Query String Values in JavaScript

As a web developer, you may come across the need to access query string parameters from the URL of a page.

Query string parameters are the values that are appended to a URL after a question mark (?).

These parameters can be used to pass data from one page to another and can also be used for various purposes such as tracking, filtering, and sorting.

In this Javascript tutorial, we will discuss how to retrieve query string parameters in JavaScript.


Introduction to Query String Parameters

A query string is a part of the URL that contains data to be passed to the server.

The data is passed in the form of key-value pairs separated by an ampersand (&).

For example, in the URL http://www.example.com?name=John&age=30, name=John and age=30 are the query string parameters.

Retrieving Query String Parameters in JavaScript

There are several methods to retrieve query string parameters in JavaScript, but the most commonly used methods are:

Using the URLSearchParams Object

The URLSearchParams object is a modern and easy way to retrieve query string parameters in JavaScript.

It is supported in modern browsers and provides a convenient way to retrieve the parameters.

const urlParams = new URLSearchParams(window.location.search);
console.log(urlParams.get('name')); // John
console.log(urlParams.get('age')); // 30

Using the split() Method

This method uses the split() method to split the query string into an array of key-value pairs.

Then, we can loop through the array and retrieve the required parameters.

const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
console.log(urlParams.get('name')); // John
console.log(urlParams.get('age')); // 30

Conclusion

In this tutorial, we discussed how to retrieve query string parameters in JavaScript.

Both methods discussed above are easy to understand and implement.

You can use either the URLSearchParams object or the split() method to retrieve the parameters based on your requirements and the compatibility of the method with your project.

I hope this tutorial helps you to retrieve query string parameters in your next project.