28

Is it possible using jquery (or just javascript) to check for the existence of a query string on the URL?

1
  • @Mic - if the question is to be taken literally (just "is it present?"), it's a different question with a much simpler answer. Commented Jul 12, 2010 at 21:03

4 Answers 4

40

Yes, the location object has a property search that contains the query string.

alert(window.location.search);
Sign up to request clarification or add additional context in comments.

Comments

32

document.location contains information about the URL, and document.location.search contains the query string, e.g. ?foo=bar&spam=eggs. As for testing its presence, how about:

if(document.location.search.length) {
    // query string exists
} else {
    // no query string exists
}

No jQuery required :o

Comments

5

I would think you could use the javascript match operator.

var url = window.location.search;
if (url.match("your string").length > 0) {
}

2 Comments

fyi, this is poor because match can return nulls, and putting length of a null object would result in an error
True. That problem can be solved via something like: if(url.indexOf("your string") !== -1)
-3

Check out http://rixi.us/post/791257125/get-and-server-free-dynamic-contet

a method to extract any query string parameters
Use::

if (_GET['key']) {
  var key = _GET['key']
}

3 Comments

-1. OP specified jQuery (or Javascript) not PHP as the language they are using.
@theringostarrs It actually is not PHP, it is just a small amount of javascript that I wrote a long while back that allows you to extract GET variables from the URL. Vastly outdated, and I'm not sure that link works anymore, but it is/was Javascript.
Why did you mix JavaScript and PHP in literally the same if-block on a JavaScript question

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.