简体   繁体   English

如何通过 JavaScript 检查查询字符串值是否存在?

[英]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

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/ .编辑:如果您对兼容性感到难过,我强烈建议使用https://github.com/medialize/URI.js/

The plain javascript code sample which answers your question literally:从字面上回答您的问题的纯 javascript 代码示例:

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:尝试查找 q 参数是否存在以及它是否具有值的纯 javascript 代码示例:

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.在现代浏览器中,这变得容易多了,这要归功于URLSearchParams接口。 This defines a host of utility methods to work with the query string of a URL.这定义了许多实用方法来处理 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 :假设我们的 URL 是https://example.com/?product=shirt&color=blue&newuser&size=m ,您可以使用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 :然后,您可以使用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:例如, URLSearchParams.get()将返回与给定搜索参数关联的第一个值:

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:您可以使用URLSearchParams.has()来检查某个参数是否存在:

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:另一种变体,但与 Gumbo 解决方案几乎相同:

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

this function help you to get parameter from URL in JS此函数帮助您从 JS 中的 URL 获取参数

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/ 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:更新已接受的答案,您可能应该只返回 if 条件,而不是明确返回 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.我插入了字符串,但您也可以像接受的答案一样将它们添加在一起。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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