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

我的URL只会有一个字符串

http://example.com?sent=yes

我只想检测:

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


当前回答

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

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

其他回答

这里有一个很棒的图书馆: https://github.com/allmarkedup/purl

这能让你做得更简单

url = 'http://example.com?sent=yes';
sent = $.url(url).param('sent');
if (typeof sent != 'undefined') { // sent exists
   if (sent == 'yes') { // sent is equal to yes
     // ...
   }
}

这个例子假设您正在使用jQuery。你也可以使用它只是简单的javascript,语法会有点不同。

这是基于Gazoris的答案,但URL解码了参数,因此当它们包含除数字和字母以外的数据时可以使用:

function urlParam(name){
    var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
    // Need to decode the URL parameters, including putting in a fix for the plus sign
    // https://stackoverflow.com/a/24417399
    return results ? decodeURIComponent(results[1].replace(/\+/g, '%20')) : null;
}

最好的解决方案。

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');

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

我用了这个,很管用。 http://codesheet.org/codesheet/NF246Tzs

function getUrlVars() {
    var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
    vars[key] = value;
    });
return vars;
}


var first = getUrlVars()["id"];