Gum*_*mbo 105
您还可以使用正则表达式:
/[?&]q=/.test(location.search)
Run Code Online (Sandbox Code Playgroud)
Lor*_*nVS 91
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
Run Code Online (Sandbox Code Playgroud)
Dam*_*che 19
使用URL:
url = new URL(window.location.href);
if (url.searchParams.get('test')) {
}
Run Code Online (Sandbox Code Playgroud)
编辑:如果你对兼容性感到难过,我强烈建议https://github.com/medialize/URI.js/.
在现代浏览器中,多亏了URLSearchParams界面,这变得容易多了。这定义了许多实用方法来处理 URL 的查询字符串。
假设我们的 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
Run Code Online (Sandbox Code Playgroud)
然后,您可以使用URLSearchParams以下方法解析查询字符串的参数:
const urlParams = new URLSearchParams(queryString);
Run Code Online (Sandbox Code Playgroud)
然后你可以在结果上调用它的任何方法。
例如,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
Run Code Online (Sandbox Code Playgroud)
您可以使用URLSearchParams.has()检查某个参数是否存在:
console.log(urlParams.has('product'));
// true
console.log(urlParams.has('paymentmethod'));
// false
Run Code Online (Sandbox Code Playgroud)
如需进一步阅读,请点击此处。
简单的javascript代码示例直接回答您的问题:
return location.search.indexOf('q=')>=0;
Run Code Online (Sandbox Code Playgroud)
普通的javascript代码示例,它尝试查找q参数是否存在以及是否具有值:
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;
Run Code Online (Sandbox Code Playgroud)
另一种变体,但与Gumbos解决方案几乎相同:
var isDebug = function(){
return window.location.href.search("[?&]debug=") != -1;
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
107187 次 |
| 最近记录: |