How to check if a query string value is present via JavaScript?

Viewed 175166

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

11 Answers

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.

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.

Related