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'

1

5 Answers 5

56

This should work:

if (window.location.search.indexOf('track=yes') > -1) {
    alert('track present');
} else {
    alert('track not here');
}
Sign up to request clarification or add additional context in comments.

Comments

4

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

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

Comments

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

Comments

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?

Comments

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...');
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.