Get url params as json object in jquery

jQuery -- Posted on April 14, 2023

This code defines a JavaScript function called getUrlParametersAsJson() that extracts URL parameters from the current page's URL and returns them as a JavaScript object (JSON format).

Here's a step-by-step explanation of how the function works:

  1. var urlParams = window.location.search.substring(1);: This line gets the URL parameters from the current page's URL, excluding the leading question mark ('?'). For example, if the URL is http://example.com/?param1=value1&param2=value2, urlParams will be "param1=value1&param2=value2".

  2. var paramArray = urlParams.split('&');: This line splits the URL parameters string into an array using the ampersand ('&') as the separator. It creates an array of strings, with each element representing a single parameter. For the example above, paramArray would be ["param1=value1", "param2=value2"].

  3. var params = {};: This initializes an empty JavaScript object that will hold the key-value pairs of the parameters.

  4. $.each(paramArray, function(index, param) {...});: This is a jQuery function that iterates over each element in the paramArray array.

  5. var keyValue = param.split('=');: This line splits each parameter string into its key and value parts based on the equal sign ('='). For example, "param1=value1" becomes ["param1", "value1"].

  6. var key = decodeURIComponent(keyValue[0]);: It decodes the key part of the parameter using decodeURIComponent() to handle any URL encoding. For instance, if the key had spaces or special characters encoded, they would be properly decoded.

  7. var value = decodeURIComponent(keyValue[1]);: Similarly, it decodes the value part of the parameter using decodeURIComponent().

  8. params[key] = value;: This assigns the decoded key and value to the params object. This line essentially adds a key-value pair to the params object for each URL parameter.

  9. Finally, the function returns the params object containing all the URL parameters in a key-value format.

The usage of the function is straightforward. By calling getUrlParametersAsJson(), you'll get an object jsonParams containing the URL parameters in JSON format. The function should work correctly as long as the URL parameters are correctly formatted, and the jQuery library is loaded on the page. The resulting jsonParams object can then be logged to the console using console.log(jsonParams).

              
                function getUrlParametersAsJson() {
  var urlParams = window.location.search.substring(1);
  var paramArray = urlParams.split('&');
  var params = {};

  $.each(paramArray, function(index, param) {
    var keyValue = param.split('=');
    var key = decodeURIComponent(keyValue[0]);
    var value = decodeURIComponent(keyValue[1]);
    params[key] = value;
  });

  return params;
}

// Usage
var jsonParams = getUrlParametersAsJson();
console.log(jsonParams);
                  
   
            

Related Posts