by Sai gowtham

How to get query parameters from a URL in JavaScript

In this tutorial, we are going to learn how to access the query parameters from a URL using JavaScript.

Query Parameters

Query parameters are added at the end of a URL using question mark ? followed by the key=value pairs.

Example:

localhost:3000/?name=sai

Accessing the query parameters

To access the query parameters of a URL inside the browser, using JavaScript, we can use the URLSeachParams interface that contains a get() method to work with it.

Here is an example:

Url:

localhost:3000/?name=sai

You can get the value of a name parameter from the above url like this:

// window.location.search = ?name=sai

const params = new URLSearchParams(window.location.search);

const name = params.get("name");

console.log(name); // "sai"

If you have multiple parameters in a URL which is passed using & operator:

localhost:3000/?name=sai&score=10

You can access it like this:

// window.location.search = ?name=sai&score=10

const params = new URLSearchParams(window.location.search);

const name = params.get("name");
const name = params.get("score");

console.log(name); // "sai"
console.log(score); // 10

You can also check, if a URL contains specified parameters or not by using the has() method.

The has() method returns boolean value true if a parameter name exists; otherwise it returns false.

params.has("name"); // true

params.has("place"); // false

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
130,921 students enrolled
21 hours of video content
View Course