如何使用 JavaScript 或 jQuery 检查查询字符串中是否包含
q=
?你也可以使用正则表达式:
/[?&]q=/.test(location.search)
if(/[?&]q=/.test(location.search)) { alert("match"); }
(由于@DragosDurlut的评论,我有点困惑:) - Leiavar field = 'q';
var url = window.location.href;
if(url.indexOf('?' + field + '=') != -1)
return true;
else if(url.indexOf('&' + field + '=') != -1)
return true;
return false
?kodiaq=1
,那么调用 url.indexOf('q=')
而没有在前面加上 &
或 ?
,会让你误以为 q
参数存在。 - michalstanko使用URL
:
url = new URL(window.location.href);
if (url.searchParams.has('test')) {
}
编辑:如果您担心兼容性问题,我强烈建议使用https://github.com/medialize/URI.js/。
编辑:请查看评论和Plabon的答案,了解为什么使用get
来检查存在性是有问题的。更好的方法是使用searchParams.has()
。
test
的值,而不是检查其是否存在。因此,如果您的查询值为?test=false
,则会返回false
。如果test
不存在,则会返回null
。您应该测试类型以确保正确性。使用has()
将是更好的选择,请参见Plabon的答案。 - WhipURLSearchParams
接口的出现,这变得更加容易了。它定义了一系列实用的方法来处理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
您可以使用URLSearchParams
来解析查询字符串的参数:
const urlParams = new URLSearchParams(queryString);
然后您可以在结果上调用其任何方法。
例如,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
你可以使用URLSearchParams.has()
来检查特定参数是否存在:console.log(urlParams.has('product'));
// true
console.log(urlParams.has('paymentmethod'));
// false
请点击此处以获取更多阅读内容。
这是一个直接回答你问题的纯 JavaScript 代码示例:
return location.search.indexOf('q=')>=0;
这是一个尝试查找参数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;
fooq=bar
返回 true。 - mickadoo还有一种变体,但几乎与Gumbo的解决方案相同:
var isDebug = function(){
return window.location.href.search("[?&]debug=") != -1;
};
试试这个
//field "search";
var pattern = /[?&]search=/;
var URL = location.search;
if(pattern.test(URL))
{
alert("Found :)");
}else{
alert("Not found!");
}
的意思是:这是一个 JSFiddle 的链接,用于展示 CodeMirror 的演示。
这个函数可以帮助您在JS中获取URL中的参数。
function getQuery(q) {
return (window.location.search.match(new RegExp('[?&]' + q + '=([^&]+)')) || [, null])[1];
}
这应该会有所帮助:
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 {};
}
}
我之前使用过这个库,它可以很好地完成你想要的任务。具体来说:
qs.contains(name)
Returns true if the querystring has a parameter name, else false.
if (qs2.contains("name1")){ alert(qs2.get("name1"));}
var url = new URLSearchParams(location.search); url.has("my_great_query");
如果该查询字符串在您的url中,则返回true
。然后,您可以使用url.get("my_great_query");
获取其值。 - user1063287