The most optimal way to get a query parameter in Javascript

I'm only working with Javascript here because this is an ad-supported landing page (landing page) and the client doesn't want jQuery to slow down web pages. I need Javascript which is the most optimal way (smallest lines of code) to get the "tid" query parameter at the landing site. For example, imagine this ad link that goes to the landing site:

http://example.com/lander1.php?tid=med01

      

Can you provide the most optimal way to get query parameters in Javascript and make it work even with IE7 and forward (FF, Chrome, Safari, Opera and IE)? Here's what I came up with, but maybe you can optimize it even more? The reason for getting this is even harsher, so that the pixel tracker is as small as possible. I mean, I already have extra lines (not shown here) to create an array of postback parameters and then call remote Javascript to pass those extra parameters to the PIWIK tracker.

try {
  var q = {};
  var ls1 = location.search.substr(1) + '&';
  var ls2 = ls1.split('&');
  for(var i1 in ls2) {
    var i2 = ls2[i1];
    q[i2.split('=')[0]] = i2.split('=')[1];
  }
} catch(e) {}

      

// Then I can use q.tid to get the "tid" query parameter in the url.

+3


source to share


3 answers


I think this might work:

var tid = '';try{tid=location.search.substr(1).split('=').join('#=').split(/=/).join('#').split('tid##')[1].split('&')[0];}catch(e){}

      



It even works if I bind to & test = 1 at the end of the url and I can even then get the "test" query parameter by replacing the "tid" above with "test".

0


source


try it



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

      

0


source


from another post here: You can also use the URI.js library by Rodney Rehm.

var qs = URI('www.mysite.com/default.aspx?dest=aboutus.aspx').query(true); 
alert(qs.tid); 

      

0


source







All Articles