JavaScript Program to get Query String Values

Last Updated : 06 Nov, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Getting query string values in JavaScript refers to extracting parameters from a URL after the "?" symbol. It allows developers to capture user input or state information passed through URLs for dynamic web content and processing within a web application.

Approach 1: Using URLSearchParams

  • In this approach, parse a URL using a URL class, and extract query parameters with searchParams.get(paramName).
  • Print parameter value if found; otherwise, indicate it's not present in the query string.

Syntax:

URLSearchParams.get(name)

Example: This example shows the use of the above-explained approach.

JavaScript
const url = require('url');

// Example URL
const str1 = 
'http://example.com/path?paramName=GeeksforGeeks';

// Parse the URL
const parsedUrl = new URL(str1);

// Get the value of a specific parameter from the query string
const paramName = 'paramName';
const result = 
    parsedUrl.searchParams.get(paramName);

if (result !== null) {
    console.log('Value of ' + 
        paramName + ' is: ' + result);
} else {
    console.log(paramName +
        ' not found in the query string.');
}

Output
Value of paramName is: GeeksforGeeks

Approach 2 : Using Pure JavaScript

  • In this approach, Create a function queryString(url) that extracts and decodes query parameters using pure JavaScript.
  • Split the URL, parse query string, and store key-value pairs.
  • Return the parameters object.

Example: This example shows the use of the above-explained approach.

JavaScript
function queryString(url) {
    const str1 = url.split('?')[1];
    const params = {};

    if (str1) {
        const pairs = str1.split('&');
        for (const pair of pairs) {
            const [key, value] = pair.split('=');
            params[key] = decodeURIComponent(value
                          .replace(/\+/g, ' '));
        }
    }

    return params;
}

const urlStr = 
'http://example.com/path?param1=GeeksforGeeks&param2=Noida';
const result = queryString(urlStr);
console.log(result);

Output
{ param1: 'GeeksforGeeks', param2: 'Noida' }

Next Article

Similar Reads