我见过很多jQuery示例,其中参数大小和名称都是未知的。

我的URL只会有一个字符串

http://example.com?sent=yes

我只想检测:

sent存在吗? 它等于"是"吗?


当前回答

如果有&在URL参数像filename="p&g.html"&uid=66

在这种情况下,第一个函数将不能正常工作。所以我修改了代码

function getUrlParameter(sParam) {
    var sURLVariables = window.location.search.substring(1).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]);
        }
    }
}

其他回答

使用这个

$.urlParam = function(name) {
  var results = new RegExp('[\?&amp;]' + name + '=([^&amp;#]*)').exec(window.location.href);
  return results[1] || 0;
}

对Sameer的回答略有改进,将参数缓存为闭包,以避免每次调用时解析和遍历所有参数

var getURLParam = (function() {
    var paramStr = decodeURIComponent(window.location.search).substring(1);
    var paramSegs = paramStr.split('&');
    var params = [];
    for(var i = 0; i < paramSegs.length; i++) {
        var paramSeg = paramSegs[i].split('=');
        params[paramSeg[0]] = paramSeg[1];
    }
    console.log(params);
    return function(key) {
        return params[key];
    }
})();

我希望使用完整的简单REG Exp

  function getQueryString1(param) {
    return decodeURIComponent(
        (location.search.match(RegExp("[?|&]"+param+'=(.+?)(&|$)'))||[,null])[1]
    );
  }

如果有&在URL参数像filename="p&g.html"&uid=66

在这种情况下,第一个函数将不能正常工作。所以我修改了代码

function getUrlParameter(sParam) {
    var sURLVariables = window.location.search.substring(1).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]);
        }
    }
}

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现在是一个包含所有参数的对象