Skip to content

Instantly share code, notes, and snippets.

@noff
Created December 25, 2013 15:59
Show Gist options
  • Save noff/8124475 to your computer and use it in GitHub Desktop.
Save noff/8124475 to your computer and use it in GitHub Desktop.
parse utm's
var source = '';
var medium = '';
var campaign = '';
var q = document.location.search;
q = q.substring(1,q.length);
q = q.split('&');
for(var a in q) {
if (q.hasOwnProperty(a)){
var b = q.split('');
if(b[0] == 'utm_source' ) {
source = b[1];
}
if(b[0] == 'utm_medium' ) {
medium = b[1];
}
if(b[0] == 'utm_campaign' ) {
campaign = b[1];
}
}
}
mixpanel.track("Lead", {
utm_source: source,
utm_medium: medium,
utm_campaign: campaign,
});
@scottbessler
Copy link

This shows up high on google SERP, and it is invalid code...

You might be better off with:

  var querystring = document.location.search;
  if (!querystring) {
    return undefined;
  }
  // remove leading ?
  querystring = querystring.substring(1);
  querystring = querystring.split('&');

  var utms = {};
  for (var i = 0; i < querystring.length; i++) {
    var part = querystring[i];
    if (part && part.length > 4 && part.startsWith("utm_")) {
      var keyValue = part.split("=");
      if (keyValue.length > 1) {
        utms[keyValue[0].substring(4)] = keyValue[1];
      }
    }
  }

  return utms;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment