tags:

views:

977

answers:

5

Hi,

How can I check if the query string contains a q= in it using javascript/jquery?

+6  A: 
var field = 'q';
var url = window.location.href;
if(url.indexOf('?' + field + '=') != -1)
    return true;
else if(url.indexOf('&' + field + '=') != -1)
    return true;
return false
LorenVS
Did you mean `'?' + field + '='`?
Joel Potter
You're right, changing, thanks for noticing
LorenVS
Ugly code. Multiple return paths, non-strict comparison operators...
J-P
Multiple return paths is a personal choice, I use them because I think they lead to cleaner code, since they help me avoid nested if statements and show exactly what is going on at a certain point in code.As for the stict cases, both the left hand and right hand sides will always be numbers, so what difference would switching to strict equality operators make?
LorenVS
Cleaner code? ... Why not just return the indexOf test, instead of placing it in a totally useless preliminary IF statement.
J-P
Because in order to return the indexOf test I would have to put them both into a single line, which would, in my mind, be harder to read. Especially considering this code was for the purpose of demonstration
LorenVS
I agree with J-P. You may have written the correct solution, but your code is really sloppy. Where are you curly braces? You should read "The Good Parts" where code written a style without curly braces has been proven to fail under certain conditions and produces confusion during maintenance.
Matthew Lock
A: 

I've used this library before which does a pretty good job of what you're after. Specifically:-

qs.contains(name)
    Returns true if the querystring has a parameter name, else false.

    if (qs2.contains("name1")){ alert(qs2.get("name1"));}
Gavin Gilmour
+4  A: 

You could also use a regular expression:

/[?&]q=/.test(location.href)
Gumbo
A: 
location.search.indexOf("q=") != -1
Eli Grey
Joel Potter
A: 

The plain javascript code sample which answers your question literally:

return location.search.indexOf('q=')>=0;

The plain javascript code sample which attempts to find if the q parameter exists and if it has a value:

var queryString=location.search;
var params=q.substring(1).split('&');
for(var i=0; i<params.length; i++){
    var pair=params[i].split('=');
    if(decodeURIComponent(pair[0])=='q' && pair[1])
     return true;
}
return false;
Peter Dolberg