Recent Posts

Showing posts with label query string. Show all posts
Showing posts with label query string. Show all posts

How to get query string values in JavaScript

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

The usage for the function would be:

var prodId = getParameterByName('prodId');

Or this another way

http://someurl.com?key=value&keynovalue&keyemptyvalue=&&keynovalue=nowhasvalue#somehash

  • Regular key/value pair (?param=value)
  • Keys w/o value (?param : no equal sign or value)
  • Keys w/ empty value (?param= : equal sign, but no value to right of equal sign)
  • Repeated Keys (?param=1&param=2)
  • Removes Empty Keys (?&& : no key or value)

  • var queryString = window.location.search || '';
    var keyValPairs = [];
    var params      = {};
    queryString     = queryString.substr(1);
    
    if (queryString.length)
    {
       keyValPairs = queryString.split('&');
       for (pairNum in keyValPairs)
       {
          var key = keyValPairs[pairNum].split('=')[0];
          if (!key.length) continue;
          if (typeof params[key] === 'undefined')
             params[key] = [];
          params[key].push(keyValPairs[pairNum].split('=')[1]);
       }
    }

How to call it:

  • params['key'];  // returns an array of values (1..n)

This is the output:

  • key            ["value"]
    keyemptyvalue  [""]
    keynovalue     [undefined, "nowhasvalue"]