简体   繁体   中英

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

如何使用 JavaScript 或 jQuery 检查查询字符串中是否包含q=

您还可以使用正则表达式:

/[?&]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/ .

The plain javascript code sample which answers your question literally:

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

The plain javascript code sample which attempts to find if the q parameter exists and if 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;

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 .

one more variant, but almost the same as Gumbos solution:

var isDebug = function(){
    return window.location.href.search("[?&]debug=") != -1;
};

this function help you to get parameter from URL in JS

function getQuery(q) {
    return (window.location.search.match(new RegExp('[?&]' + q + '=([^&]+)')) || [, null])[1];
}

Try this

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

I've used this library before which does a pretty good job of what you're after. Specifically:-

qs.contains(name)
    Returns true if the querystring has a parameter name, else false.

    if (qs2.contains("name1")){ alert(qs2.get("name1"));}

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 {};
    }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM