Skip to main content

This function will get the value of a query string parameter from the current URL, or specified URL.

function getQueryString(parameter, searchQuery) {
  if (!searchQuery) {
    searchQuery = window.location.search;
  }

  var match = RegExp('[?&]' + parameter + '=([^&]*)').exec(searchQuery);
  return match ? decodeURIComponent(match[1].replace(/\+/g, ' ')) : null;
}

// USAGE EXAMPLES
var q = '?i=main&mode=front&sid=de8d49b78a85a322c4155015fdce22c4&enc=+Hello%20&empty';

console.log(getQueryString('i', q));    // outputs: main
console.log(getQueryString('mode', q)); // outputs: front
console.log(getQueryString('sid', q));  // outputs: de8d49b78a85a322c4155015fdce22c4
console.log(getQueryString('enc', q));  // outputs:  Hello