Open In App

JavaScript Program to get Query String Values

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

Syntax:

URLSearchParams.get(name)

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






const url = require('url');
  
// Example URL
const str1 = 
  
// 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

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




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 = 
const result = queryString(urlStr);
console.log(result);

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

Article Tags :