23

I am trying to make my page perform an action only if it sees that a particular parameter is present in the url.

I essentially want the javascript code to do this:

consider an example page such as: http://www.example.com?track=yes

If a page loads that contains the parameter 'track' within the url, print 'track exists', else if the 'track' parameter doesn't exist print 'track does not exist'

Cœur
  • 34,719
  • 24
  • 185
  • 251
rob melino
  • 761
  • 2
  • 10
  • 18

5 Answers5

55

This should work:

if (window.location.search.indexOf('track=yes') > -1) {
    alert('track present');
} else {
    alert('track not here');
}
deviousdodo
  • 9,113
  • 2
  • 28
  • 34
4

Use something like the function from Artem's answer in this SO post:

if (getParameterByName('track') != '') {
   alert ('run track');
}
Community
  • 1
  • 1
JW8
  • 1,456
  • 4
  • 21
  • 36
1

It's not hard to split up the query string to find the relevant bits:

var path = location.substr(1), // remove ?
    queryBits = path.split('&'),
    parameters = {},
    i;

for (i = 0 ; i < queryBits.length ; i++) {
    (function() { // restrict keyval to a small scope, don't need it elsewhere
        var keyval = queryBits[i].split('=');
        parameters[decodeURIComponent(keyval[0])] = decodeURIComponent(keyval[1]);
    }());
}

// parameters now holds all the parts of the URL as key-value pairs

if (parameters.track == 'yes') {
   alert ('track exists');
} else {
    alert ("it doesn't");
}
lonesomeday
  • 224,675
  • 49
  • 309
  • 312
0

What you're looking for is called the Query String or Query Parameter. See this function to get it w/o the use of plugins like jQuery: How can I get query string values in JavaScript?

Community
  • 1
  • 1
Chazbot
  • 1,860
  • 1
  • 13
  • 23
0

You can use the window.location.search property:

if(/(^|&)track(&|$)/.test(window.location.search.substring(1))) {
    alert('track exists!');
} else {
    alert('it doesn\'t...');
}
Ry-
  • 209,133
  • 54
  • 439
  • 449