Open In App

How to get URL Parameters using JavaScript ?

In this article, we will learn how to get the URL parameters in Javascript, along with understanding their implementation through the examples.

For getting the URL parameters, there are 2 ways:



Method 1: Using the URLSearchParams Object

Syntax:

let paramString = urlString.split('?')[1];
let queryString = new URLSearchParams(paramString);
for (let pair of queryString.entries()) {
console.log("Key is: " + pair[0]);
console.log("Value is: " + pair[1]);
}

Example: This example illustrates the use of the URLSearchParams Object to get the URL parameter.






<!DOCTYPE html>
<html>
<head>
    <title>
          How To Get URL Parameters using JavaScript?
      </title>
</head>
 
<body>
    <h1 style="color:green;">
        GeeksforGeeks
    </h1>
    <b>
        How To Get URL Parameters
        With JavaScript?
    </b>
    <p> The url used is:
    </p>
 
    <p>
       Click on the button to get the url
       parameters in the console.
    </p>
 
    <button onclick="getParameters()"> Get URL parameters </button>
    <script>
    function getParameters() {
        let urlString =
        let paramString = urlString.split('?')[1];
        let queryString = new URLSearchParams(paramString);
        for(let pair of queryString.entries()) {
            console.log("Key is:" + pair[0]);
            console.log("Value is:" + pair[1]);
        }
    }
    </script>
</body>
</html>

Output:

 entries() Method

Method 2: Separating and accessing each parameter pair

Syntax:

let paramString = urlString.split('?')[1];
let params_arr = paramString.split('&');
for (let i = 0; i < params_arr.length; i++) {
let pair = params_arr[i].split('=');
console.log("Key is:", pair[0]);
console.log("Value is:", pair[1]);
}

Example: This example illustrates the Separate access for each parameter pair.




<!DOCTYPE html>
<html>
<head>
    <title>
          How To Get URL Parameters using JavaScript?
      </title>
</head>
 
<body>
    <h1 style="color:green;">
        GeeksforGeeks
    </h1> <b>
        How To Get URL Parameters
        With JavaScript?
    </b>
    <p> The url used is:
    </p>
 
    <p>
       Click on the button to get the url
       parameters in the console.
    </p>
 
    <button onclick="getParameters()"> Get URL parameters </button>
    <script>
    function getParameters() {
        let urlString =
        let paramString = urlString.split('?')[1];
        let params_arr = paramString.split('&');
        for(let i = 0; i < params_arr.length; i++) {
            let pair = params_arr[i].split('=');
            console.log("Key is:" + pair[0]);
            console.log("Value is:" + pair[1]);
        }
    }
    </script>
</body>
</html>

Output:


Article Tags :