Query Variable Function

/ Published in: JavaScript
Save to your folder(s)

This function extracts a value from a url. Very useful for tracking codes. For example, you have a url http://your.url/?source=666999, and you need the source number to be placed into a variable. Use the code below.

Copy this code and paste it in your HTML
  1. variable = getQueryVariable("what you want to extract");//e.g "source"
  3. function getQueryVariable(variable) {
  4. var query = window.location.search.substring(1);
  5. var vars = query.split("&");
  6. for (var i=0;i<vars.length;i++) {
  7. var pair = vars[i].split("=");
  8. if (pair[0] == variable) {
  9. return pair[1];
  10. }
  11. }
  12. }

Report this snippet


RSS Icon Subscribe to comments

You need to login to post a comment.