我见过很多jQuery示例,其中参数大小和名称都是未知的。
我的URL只会有一个字符串
http://example.com?sent=yes
我只想检测:
sent存在吗? 它等于"是"吗?
我见过很多jQuery示例,其中参数大小和名称都是未知的。
我的URL只会有一个字符串
http://example.com?sent=yes
我只想检测:
sent存在吗? 它等于"是"吗?
当前回答
只是想展示一下我的代码:
function (name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
其他回答
2023年起的解决方案
我们有:http://example.com?sent=yes
let searchParams = new URLSearchParams(window.location.search)
sent存在吗?
searchParams.has('sent') // true
它等于"是"吗?
let param = searchParams.get('sent')
然后比较一下。
使用这个
$.urlParam = function(name) {
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
return results[1] || 0;
}
我希望使用完整的简单REG Exp
function getQueryString1(param) {
return decodeURIComponent(
(location.search.match(RegExp("[?|&]"+param+'=(.+?)(&|$)'))||[,null])[1]
);
}
使用URLSearchParams:
var params = new window.URLSearchParams(window.location.search);
console.log(params.get('name'));
注意兼容性(大多数情况下是好的,但IE和Edge,可能是不同的故事,检查这个兼容性参考:https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams)
最好的解决方案。
var getUrlParameter = function getUrlParameter(sParam) {
var sPageURL = window.location.search.substring(1),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
}
}
return false;
};
这就是你如何使用这个函数假设URL是, http://dummy.com/?technology=jquery&blog=jquerybyexample。
var tech = getUrlParameter('technology');
var blog = getUrlParameter('blog');