Friday, January 30, 2015

How to get the value from the URL parameter?

Here is a recursive solution that has no regex, and has minimal mutation (only the params object is mutated, which I believe is unavoidable in JS).
It's awesome because it:
  • Is recursive
  • Handles multiple parameters of the same name
  • Deals well with malformed parameter strings (missing values, so on)
  • Doesn't break if '=' is in the value
  • Performs URL decoding
  • IS RECURSIVE!
function getUrlVars() {
    var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,  
    function(m,key,value) {
      vars[key] = value;
    });
    return vars;
  }
var fType = getUrlVars()["type"];

No comments:

Post a Comment