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

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

+77
javascript
Aug 21 '09 at 21:52
source share
9 answers
 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 
+87
Aug 21 '09 at 21:54
source share

You can also use regex:

 /[?&]q=/.test(location.search) 
+100
Aug 21 '09 at 22:04
source share

Using URL :

 url = new URL(window.location.href); if (url.searchParams.get('test')) { } 

EDIT: if you are sad about compatibility, I highly recommend https://github.com/medialize/URI.js/ .

+14
Feb 15 '18 at 2:48
source share

A simple JavaScript code example that answers your question literally:

 return location.search.indexOf('q=')>=0; 

A simple JavaScript code example that tries to find if the q parameter exists and whether 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; 
+9
Aug 21 '09 at 22:07
source share

another option, but almost the same as the Gumbos solution:

 var isDebug = function(){ return window.location.href.search("[?&]debug=") != -1; }; 
+5
Jun 12 '14 at 8:34
source share

this function will help you get parameter from url in js

 function getQuery(q) { return (window.location.search.match(new RegExp('[?&]' + q + '=([^&]+)')) || [, null])[1]; } 
+3
Mar 04 '16 at 22:48
source share

try it

 //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/

+3
Jul 17 '17 at 10:44
source share

I used this library , before which what you need works pretty well. In particular: -

 qs.contains(name) Returns true if the querystring has a parameter name, else false. if (qs2.contains("name1")){ alert(qs2.get("name1"));} 
0
Aug 21 '09 at 21:55
source share

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 {}; } } 
0
Apr 09 '15 at 19:00
source share



All Articles