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
  • 37,241
  • 25
  • 195
  • 267
rob melino
  • 781
  • 2
  • 10
  • 18

5 Answers5

56

This should work:

if (window.location.search.indexOf('track=yes') > -1) {
    alert('track present');
} else {
    alert('track not here');
}
deviousdodo
  • 9,177
  • 2
  • 29
  • 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,496
  • 5
  • 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
  • 233,373
  • 50
  • 316
  • 318
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,890
  • 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-
  • 218,210
  • 55
  • 464
  • 476