Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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

like image 523
mrblah Avatar asked Aug 21 '09 21:08

mrblah


People also ask

How do I check if a query string parameter exists?

Check if a query string parameter existsThe URLSearchParams.has() method returns true if a parameter with a specified name exists.

What is query string in Javascript?

A query string is part of the full query, or URL, which allows us to send information using parameters as key-value pairs.

How do I check if a URL contains a string?

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.

Which Javascript statement can you use to retrieve a query string from the current web page's URL and assign it to the queryString variable?

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.


3 Answers

You could also use a regular expression:

/[?&]q=/.test(location.search)
like image 185
Gumbo Avatar answered Oct 13 '22 21:10

Gumbo


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
like image 26
LorenVS Avatar answered Oct 13 '22 23:10

LorenVS


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().

like image 48
Damien Roche Avatar answered Oct 13 '22 23:10

Damien Roche