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=w3wiki¶m2=Noida';
const result = queryString(urlStr);
console.log(result);


Output

{ param1: 'w3wiki', param2: 'Noida' }


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.

Table of Content

  • Using URLSearchParams
  • Using Pure JavaScript

Similar Reads

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....

Approach 2 : Using Pure JavaScript

...