How can I check if the query string contains a q=
in it using JavaScript or jQuery?
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.