Get Query String Value From URL Using JavaScript

The query string is like an add-on for a URL, giving extra details to a web page’s link. It’s introduced by a question mark ‘?’ and is used to attach values to parameters.

page-url.html?parameter=value

Example –

tutorial.html?id=1

When there’s more than one piece of extra information, they’re linked together using an ampersand ‘&’. Just a tip: make sure not to put the query string value in quotation marks – they’re not needed! This little trick lets websites understand what you’re looking for and helps you get the right content.

page-url.html?parameter1=value1&parameter2=value2

Example –

tutorial.html?id=2&name=js

 

How to Get Query String From URL Using JavaScript

You may need to get query string values from a URL using JavaScript dynamically. So, you have to learn it with this tutorial which is very easy to understand and implement in the project.

Learn More –

Convert HTML to PDF in JavaScript

Export HTML Table to Excel using JavaScript

Let’s get started with two ways.

1. Get Query String Value using ‘URLSearchParams’

new URLSearchParams(window.location.search);: Create a new object to handle query parameters from the current URL.

urlParams.get('param');: Retrieve the value of the ‘param’ query parameter from the object created in the previous line.

const urlParams = new URLSearchParams(window.location.search);
const paramValue = urlParams.get('param');

For Example –

Suppose the current URL is https://tutorial.html?id=2&name=js

If you want to get the value of ‘id’ then you can write the following code

const currentURL = new URLSearchParams(window.location.search); 
const id = currentURL.get('id');

console.log(id)

If you want to get the value of ‘name; then you can write the following code

const currentURL = new URLSearchParams(window.location.search); 
const id = currentURL.get('name');

console.log(id)

2. Manually Parse Query String

function getQueryParamValue(paramName) {
  const queryString = window.location.search.substring(1); // Remove the leading "?"
  const queryParams = queryString.split('&'); // Split parameters by "&"

  let paramValue = null;

  for (const param of queryParams) {
    const [key, value] = param.split('=');
    if (key === paramName) {
      paramValue = decodeURIComponent(value); // Decode URL-encoded value
      break;
    }
  }

  return paramValue;
}

 

Suppose the current URL is https://tutorial.html?id=2&name=js

If you want to get the value of ‘id’ then you can write the following code

const value = getQueryParamValue('id');
console.log(value);

If you want to get the value of ‘name’ then you can write the following code

const value = getQueryParamValue('name');
console.log(value);

Steps to Get Query String Value with javascript

We are developing a functionality that enables the retrieval of query string values from URLs when they are clicked. This feature will greatly assist in obtaining and utilizing query string parameters from various linked pages that require navigation.

1. Create Links with Query String

Now, Create some links with query string and will get its query string value while clicking on those links dynamically

File Name – index.php

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class="query-string">
    <a href="index.php?id=1&language=html">HTML</a>
    <a href="index.php?id=2&language=css">CSS</a>
    <a href="index.php?id=3&language=javascript">JavaScript</a>
    <a href="index.php?id=4&language=php">PHP</a>
   
    <br><br>
    <div id="result"></div>
</div>
<script type="text/javascript" src="custom.js"></script>
</body>
</html>

Steps to write code:

  • Start with a `<div>` as a container for query string links.
  • Create an anchor link `<a>` with the URL and text “HTML”.
  • Add another anchor link with a distinct URL and text “CSS”.
  • Introduce an anchor link with different URL and text “JavaScript”.
  •  Include an anchor link with unique URL and text “PHP”.
  • Insert two line breaks for spacing.
  • Set up a `<div>` with the ID “result” to display query string values.
  • Close the “query-string” `<div>` tag.
  • Link an external JavaScript file named “custom.js” for handling interaction.

3. Get Query String Value Using JavaScript Function

File Name – custom.js

document.addEventListener("DOMContentLoaded", function() {
    var links = document.querySelectorAll(".query-string a");
    var resultDiv = document.getElementById("result");

    links.forEach(function(link) {
        link.addEventListener("click", function(event) {
            event.preventDefault();
            var queryString = link.getAttribute("href").split("?")[1];
            var params = new URLSearchParams(queryString);
            
            var values = [];
            params.forEach(function(value, key) {
                values.push(key + ": " + value);
            });

            resultDiv.innerHTML = values.join("<br>");
        });
    });
});

Steps to write code –

  • load document completely with the “DOMContentLoaded” event.
  • Select anchor elements inside elements with the class “query-string” and store them.
  • Get the DOM element with the ID “result” to display query string values.
  • Loop through each link and set up a click event listener.
  • On link click, prevent default navigation behavior.
  • Extract the query string from the clicked link’s href.
  • Parse the query string into parameters using URLSearchParams.
  • Initialize an array to hold key-value pairs from the parameters.
  • Loop through parameters, and add formatted key-value pairs to the array.
  • Update the resultDiv content with the array, separated by line breaks.