Get parameters from URL using Javascript

Get parameters from URL using Javascript

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.

The Script

[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);

Here’s the Javascript in full

[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//

Test

- 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


Tags:

About the Author

John Lufadeju

  • http://www.javascriptbank.com/ Javascript Examples

    great tips, thank

  • http://www.javascriptbank.com/ Javascript Examples

    great tips, thank

  • Nancy

    Nice post! I was looking for code like this the other day and was introduced to jPaq’s GET object. It is basically an associative array containing all of the URL’s parameters. Here is an example that Chris West posted in jsbin.com: http://jsbin.com/checkerboard/2

  • Become a Fan


    Your Blog Tools on Facebook
  • Build Your Team

  • Article Marketing Tool

    Submit a different unique article to hundreds of sites
local seo
buy groceries online
average credit card processing fees
RankPay