130

How can I check if the query string contains a q= in it using JavaScript or jQuery?

user1063287
  • 10,265
  • 25
  • 122
  • 218
mrblah
  • 99,669
  • 140
  • 310
  • 420
  • 3
    This might be of help too: https://stackoverflow.com/a/12151322 - contains information about [URLSearchParams](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/URLSearchParams), eg: `var url = new URLSearchParams(location.search); url.has("my_great_query");` returns `true` if that query string is in your url. You can then get its value with `url.get("my_great_query");`. – user1063287 Jul 05 '19 at 13:53
  • This is by far the cleanest way to parse variables as URL decoding is also automatically handled! – Juha Vehnia Jun 14 '23 at 02:29

12 Answers12

129

You could also use a regular expression:

/[?&]q=/.test(location.search)
Gumbo
  • 643,351
  • 109
  • 780
  • 844
  • 1
    actually it would lok more like: if (!new RegExp("[?&]hfPageToken=").test(s.data)) // if hfPageToken data is not already present in the request { s.data = s.data ? [s.data, tokenParam].join("&") : tokenParam; } – Dragos Durlut Oct 10 '12 at 10:29
  • 11
    Just to clarify, this works great `if(/[?&]q=/.test(location.search)) { alert("match"); }` (I was a bit confused due to @DragosDurlut comment. :) – Leia Apr 24 '17 at 04:24
  • 3
    Yoda would say regarding regular expressions: "Shorter code they are.. easier to read they are not". – RayLoveless Dec 24 '19 at 00:03
128
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
  • 12,597
  • 10
  • 47
  • 54
  • 7
    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 Aug 21 '09 at 22:17
  • 4
    Cleaner code? ... Why not just return the indexOf test, instead of placing it in a totally useless preliminary IF statement. – James Aug 21 '09 at 23:09
  • 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 Aug 22 '09 at 03:52
  • 4
    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. –  Aug 22 '09 at 08:12
  • 1
    Sometimes cgi apps like perl use the semicolon (;) instead of ampersand as a parameter (which is valid in the http spec). You need to use [&;] where you've used & – Matthew Lock Oct 28 '09 at 01:47
  • 2
    url.indexOf(field + '=') != -1 was enough I think. It doesn't matter if it is in the beginning or not – yyy Oct 07 '11 at 18:30
  • 3
    @yyy No it wasn't. If you had a query string like `?kodiaq=1`, then calling `url.indexOf('q=')` without prefixing it with `&` or `?` would lead you to believe that the `q` parameter is present. – michalstanko Jan 19 '18 at 08:55
63

Using URL:

url = new URL(window.location.href);

if (url.searchParams.has('test')) {

}

EDIT: if you're sad about compatibility, I'd highly suggest https://github.com/medialize/URI.js/.

EDIT: see comment and Plabon's answer for why using get is problematic to check existence. Much better to use searchParams.has().

Damien Roche
  • 13,189
  • 18
  • 68
  • 96
21

In modern browsers, this has become a lot easier, thanks to the URLSearchParams interface. This defines a host of utility methods to work with the query string of a URL.

Assuming that our URL is https://example.com/?product=shirt&color=blue&newuser&size=m, you can grab the query string using window.location.search:

const queryString = window.location.search;
console.log(queryString);
// ?product=shirt&color=blue&newuser&size=m

You can then parse the query string’s parameters using URLSearchParams:

const urlParams = new URLSearchParams(queryString);

Then you can call any of its methods on the result.

For example, URLSearchParams.get() will return the first value associated with the given search parameter:

const product = urlParams.get('product')
console.log(product);
// shirt

const color = urlParams.get('color')
console.log(color);
// blue

const newUser = urlParams.get('newuser')
console.log(newUser);
// empty string

You can use URLSearchParams.has() to check whether a certain parameter exists:

console.log(urlParams.has('product'));
// true

console.log(urlParams.has('paymentmethod'));
// false

For further reading please click here.

Plabon Dutta
  • 6,819
  • 3
  • 29
  • 33
10

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=queryString.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
  • 2,027
  • 16
  • 21
5

one more variant, but almost the same as Gumbos solution:

var isDebug = function(){
    return window.location.href.search("[?&]debug=") != -1;
};
Humppakäräjät
  • 1,156
  • 2
  • 13
  • 17
3

this function help you to get parameter from URL in JS

function getQuery(q) {
    return (window.location.search.match(new RegExp('[?&]' + q + '=([^&]+)')) || [, null])[1];
}
Bafi
  • 565
  • 5
  • 7
3

Try this

//field "search";
var pattern = /[?&]search=/;
var URL = location.search;

if(pattern.test(URL))
{
    alert("Found :)");
}else{
    alert("Not found!");
}

JSFiddle: https://jsfiddle.net/codemirror/zj4qyao2/

codemirror
  • 3,164
  • 29
  • 42
0

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
  • 6,833
  • 4
  • 40
  • 44
0

This should help:

function getQueryParams(){
    try{
        url = window.location.href;
        query_str = url.substr(url.indexOf('?')+1, url.length-1);
        r_params = query_str.split('&');
        params = {}
        for( i in r_params){
            param = r_params[i].split('=');
            params[ param[0] ] = param[1];
        }
        return params;
    }
    catch(e){
       return {};
    }
}
Killswitch
  • 346
  • 2
  • 12
0

Update on the accepted answer, you should probably just return the if conditions, rather than explicitly returning true/false:

const field = 'q';
const url = window.location.href;
return url.indexOf(`?${field}=`) !== -1 || url.indexOf(`&${field}=`) !== -1;

I interpolated the strings, but you can also just add them together as in the accepted answer.

Robin G
  • 307
  • 2
  • 12
0

In my case, I wanted to get the value of q as well. I ended up doing this. I hope anyone find this helpful.

    if(/[?&]q=/.test(location.search)) {
        const params = new URLSearchParams(location.search);
        return params.get('q');
    }
Tomer Gal
  • 933
  • 12
  • 21