Get the Query String with Javascript as Associative Array

Here is my javacript function to get the query string into an associative array of field-value pairs:

function getQueryString() {
  var vars = [];

  // Get the start index of the query string
  var qsi = window.location.href.indexOf('?');
  if (qsi == -1)
    return vars;

  // Get the query string
  var qs = window.location.href.slice(qsi + 1);

  // Check if there is a subsection reference
  sri = qs.indexOf('#');
  if (sri >= 0)
    qs = qs.slice(0, sri);

  // Build the associative array
  var hashes = qs.split('&');
  for (var i = 0; i < hashes.length; i++) {
    var sep = hashes[i].indexOf('=');
    if (sep <= 0)
      continue;
    var key = decodeURIComponent(hashes[i].slice(0, sep));
    var val = decodeURIComponent(hashes[i].slice(sep + 1));
    vars[key] = val;
  }

  return vars;
}

Example usage:

// Get the query string
var queryString = getQueryString();

// Print all field-value pairs
for (var k in queryString)
  console.log(k + " ==> " + queryString[k]);

// Check if the field "a" exists
if (queryString["a"] !== undefined)
  console.log(queryString["a"]);

// Get the value for the field "b"
var b = queryString["b"];

// Assign a value for the field "b"
queryString["b"] = "10";

Categories

Category BootstrapCategory CoffeescriptCategory DrupalCategory GravCategory HTMLCategory JavascriptCategory JoomlaCategory jQueryCategory LaravelCategory MagentoCategory PHPCategory SharePointCategory SpringCategory ThymeleafCategory WordPressCategory Workflow

Comments

Developed and designed by Netgloo
© 2019 Netgloo