During one of my consulting projects, I had the task of extracting a tracking/campaign ID from a URL and displaying it on a page.
Something along the lines of
http://www.buildasuperstarblog.com/work.html?track_id=12345&page=work
This test URL contains tracking id “12345″ and a page titled “work”.
For campaign and data gathering purposes, you may wish to extract these parameters.
To achieve this, I have embedded a Javascript function within my html page.
[1] Using regular expression, the first part of the function reads the page URL and returns the value.
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
[2] The second part lets you assign a variable to your URL parameters and then writes the values to the page.
var tracking_id = getUrlVars()["WT.mc_id"];
var page_source = getUrlVars()["page"];
document.write(tracking_id);
document.write(page_source);
[3] Embbeded within HTML
//Start of script//
var tracking_id = getUrlVars()["track_id"];
var page_source = getUrlVars()["page"];
document.write(tracking_id);
//document.write(page_source);
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
//end of script//
- To test this, simply copy and paste section 3 into a blank HTML page.
- Upload to your web server.
- Load the page. (At this stage you will see a blank page)
- Now at the end of your URL add the following parameters …/yourfilename.html?track_id=12345&page=work.
- Your page should now display “12345″ “work”
All done