我见过很多jQuery示例,其中参数大小和名称都是未知的。
我的URL只会有一个字符串
http://example.com?sent=yes
我只想检测:
sent存在吗? 它等于"是"吗?
我见过很多jQuery示例,其中参数大小和名称都是未知的。
我的URL只会有一个字符串
http://example.com?sent=yes
我只想检测:
sent存在吗? 它等于"是"吗?
当前回答
不可否认,我是在为一个过度回答的问题补充我的答案,但这有以下优点:
——不依赖于任何外部库,包括jQuery
—不污染全局函数名称空间,通过扩展'String'
—不创建任何全局数据,并在匹配后进行不必要的处理
处理编码问题,并接受(假设)非编码参数名
——避免显式的for循环
String.prototype.urlParamValue = function() {
var desiredVal = null;
var paramName = this.valueOf();
window.location.search.substring(1).split('&').some(function(currentValue, _, _) {
var nameVal = currentValue.split('=');
if ( decodeURIComponent(nameVal[0]) === paramName ) {
desiredVal = decodeURIComponent(nameVal[1]);
return true;
}
return false;
});
return desiredVal;
};
然后你可以这样使用它:
var paramVal = "paramName".urlParamValue() // null if no match
其他回答
也许太晚了。但是这种方法非常简单易行
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.url.js"></script>
<!-- URL: www.example.com/correct/?message=done&year=1990 -->
<script type="text/javascript">
$(function(){
$.url.attr('protocol') // --> Protocol: "http"
$.url.attr('path') // --> host: "www.example.com"
$.url.attr('query') // --> path: "/correct/"
$.url.attr('message') // --> query: "done"
$.url.attr('year') // --> query: "1990"
});
更新 需要url插件:plugins.jquery.com/url 由于-Ripounet
$.urlParam = function(name) {
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
return results[1] || 0;
}
Sameer回答的咖啡脚本版本
getUrlParameter = (sParam) ->
sPageURL = window.location.search.substring(1)
sURLVariables = sPageURL.split('&')
i = 0
while i < sURLVariables.length
sParameterName = sURLVariables[i].split('=')
if sParameterName[0] == sParam
return sParameterName[1]
i++
var RequestQuerystring; (窗口。Onpopstate = function () { var匹配, pl = /\+/g, //用空格替换加法符号的正则表达式 搜索= /([^&=]+)=?([^&]*)/g, decode =函数(s){返回decodeURIComponent(s)。替换(pl, " "));}, Query = window.location.search.substring(1); RequestQuerystring = {}; While (match = search.exec(查询)) RequestQuerystring[decode(match[1])] = decode(match[2]); })();
RequestQuerystring现在是一个包含所有参数的对象
2023年起的解决方案
我们有:http://example.com?sent=yes
let searchParams = new URLSearchParams(window.location.search)
sent存在吗?
searchParams.has('sent') // true
它等于"是"吗?
let param = searchParams.get('sent')
然后比较一下。