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

我的URL只会有一个字符串

http://example.com?sent=yes

我只想检测:

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


当前回答

这可能有点过分了,但是现在有一个非常流行的用于解析uri的库,叫做URI.js。

例子

var uri = "http://example.org/foo.html?technology=jquery&technology=css&blog=stackoverflow"; var components = URI.parse(uri); var query = URI.parseQuery(components['query']); document.getElementById("result").innerHTML = "URI = " + uri; document.getElementById("result").innerHTML += "<br>technology = " + query['technology']; // If you look in your console, you will see that this library generates a JS array for multi-valued queries! console.log(query['technology']); console.log(query['blog']); <script src="https://cdnjs.cloudflare.com/ajax/libs/URI.js/1.17.0/URI.min.js"></script> <span id="result"></span>

其他回答

2023年起的解决方案

我们有:http://example.com?sent=yes

let searchParams = new URLSearchParams(window.location.search)

sent存在吗?

searchParams.has('sent') // true

它等于"是"吗?

let param = searchParams.get('sent')

然后比较一下。

还有另一种功能……

function param(name) {
    return (location.search.split(name + '=')[1] || '').split('&')[0];
}

函数GetRequestParam(参数) { Var res = null; 尝试{ var qs = decodeURIComponent(window.location.search.substring(1));//获取then之后的所有内容'?URI中的' Var ar = q .split('&'); 美元。Each (ar, function(a, b){ Var kv = b.split('='); If (param === kv[0]){ Res = kv[1]; 返回false;//打破循环 } }); }捕捉(e) {} 返回res; }

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