How can I check if the query string contains a q=
in it using JavaScript or jQuery?
Check if a query string parameter existsThe URLSearchParams.has() method returns true if a parameter with a specified name exists.
A query string is part of the full query, or URL, which allows us to send information using parameters as key-value pairs.
Use indexOf() to Check if URL Contains a String When a URL contains a string, you can check for the string's existence using the indexOf method from String. prototype. indexOf() . Therefore, the argument of indexOf should be your search string.
You can simply use URLSearchParams() . Lets see we have a page with url: https://example.com/?product=1&category=game. On that page, you can get the query string using window.
You could also use a regular expression:
/[?&]q=/.test(location.search)
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
Using URL
:
url = new URL(window.location.href);
if (url.searchParams.get('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 below for why using get
is problematic to check existence. Much better to use searchParams.has()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With