use javascript to find parameter in url and then apply if then logic

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:

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’

This should work:

if ('track=yes') > -1) {
    alert('track present');
} else {
    alert('track not here');

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

if (getParameterByName('track') != '') {
   alert ('run track');

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 = {},

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

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?

You can use the property:

if(/(^|&)track(&|$)/.test( {
    alert('track exists!');
} else {
    alert('it doesn\'t...');

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .
Read More:   How do I animate a scale css property using jquery?

Similar Posts