3

I'm working with Javascript only here because this is an advertising lander (landing page) and the client doesn't want jQuery slowing down web pages. I need some Javascript that is the most optimal way (least lines of code) to get the 'tid' query parameter on the lander. For instance, imagine this advertisement link that goes to a lander:

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 from IE7 and forward (FF, Chrome, Safari, Opera, and IE)? Here's what I've come up with, but perhaps you can optimize it even tighter? The reason for getting this even tighter is so that the snippet for the pixel tracking is as small as possible. I mean, I'm already having extra lines (not shown here) to create an array of postback parameters, and then calling a remote Javascript to pass these extra parameters to the PIWIK tracking system.

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) {}

// I can then use q.tid to get the 'tid' query parameter on the URL.

Joseph
  • 117,725
  • 30
  • 181
  • 234
Volomike
  • 23,743
  • 21
  • 113
  • 209

3 Answers3

0

Try this

 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, " "));
    };
Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59
0

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

var qs = URI('www.mysite.com/default.aspx?dest=aboutus.aspx').query(true); 
alert(qs.tid); 
Reflective
  • 3,854
  • 1
  • 13
  • 25
  • too many lines of Javascript -- I'm not gaining anything on page load speed – Volomike Jul 17 '15 at 18:55
  • Usually the speed is dependent on repeating actions, not on 1 time parsing, but probably you know better than me the speed you need. anyway, that's an easy and not slow way to get your params in reliable style. If you need speed, do a regex just for the param you need - `tid` ... no faster way than that, you don't need to parse all params if you need just `tid` and a lot of speed! – Reflective Jul 17 '15 at 19:16
0

I think this can work:

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

This even works if I tack on &test=1 on the end of the URL, and I can even then get 'test' query parameter by swapping 'tid' above with 'test'.

Volomike
  • 23,743
  • 21
  • 113
  • 209
  • Actually this [one](http://stackoverflow.com/a/13403640/105539) is even better and shorter, as long as it's wrapped with try/catch. – Volomike Jul 17 '15 at 19:12