我有一个带有一些GET参数的URL,如下所示:

www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5 

我需要得到c的全部值。我试图读取URL,但只得到m2。如何使用JavaScript执行此操作?


当前回答

// Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

// Usage for URL: http://my.site.com/location?locationId=53cc272c0364aefcb78756cd&shared=false
var id = getUrlVars()["locationId"];

从这里得到:http://jquery-howto.blogspot.ru/2009/09/get-url-parameters-values-with-jquery.html

其他回答

还有一个建议。

已经有一些很好的答案,但我发现它们不必要地复杂,难以理解。这是一个简短、简单的数组,它返回一个简单的关联数组,其中键名与URL中的令牌名相对应。

我为那些想学习的人添加了一个带有评论的版本。

注意,它的循环依赖于jQuery($.each),我建议使用jQuery而不是forEach。我发现,全面使用jQuery来确保跨浏览器兼容性比插入单独的补丁来支持旧浏览器不支持的新功能更简单。

编辑:在我写了这篇文章后,我注意到埃里克·埃利奥特的回答几乎相同,尽管它使用了forEach,而我通常反对(出于上述原因)。

function getTokens(){
    var tokens = [];
    var query = location.search;
    query = query.slice(1);
    query = query.split('&');
    $.each(query, function(i,value){    
        var token = value.split('=');   
        var key = decodeURIComponent(token[0]);     
        var data = decodeURIComponent(token[1]);
        tokens[key] = data;
    });
    return tokens;
}

注释版本:

function getTokens(){
    var tokens = [];            // new array to hold result
    var query = location.search; // everything from the '?' onward 
    query = query.slice(1);     // remove the first character, which will be the '?' 
    query = query.split('&');   // split via each '&', leaving us an array of something=something strings

    // iterate through each something=something string
    $.each(query, function(i,value){    

        // split the something=something string via '=', creating an array containing the token name and data
        var token = value.split('=');   

        // assign the first array element (the token name) to the 'key' variable
        var key = decodeURIComponent(token[0]);     

        // assign the second array element (the token data) to the 'data' variable
        var data = decodeURIComponent(token[1]);

        tokens[key] = data;     // add an associative key/data pair to our result array, with key names being the URI token names
    });

    return tokens;  // return the array
}

对于下面的示例,我们将假设此地址:

http://www.example.com/page.htm?id=4&name=murray

您可以将URL令牌分配给自己的变量:

var tokens = getTokens();

然后按名称引用每个URL令牌,如下所示:

document.write( tokens['id'] );

这将打印“4”。

您也可以直接从函数中引用一个令牌名称:

document.write( getTokens()['name'] );

…上面会印着“murray”。

这是有效的:

function getURLParameter(name) {
  return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [null, ''])[1].replace(/\+/g, '%20')) || null;
}

我没有得到任何其他最好的答案。

我写了一个更简单优雅的解决方案。

var arr = document.URL.match(/room=([0-9]+)/)
var room = arr[1];

简单的方法

function getParams(url){
        var regex = /[?&]([^=#]+)=([^&#]*)/g,
            params = {},
            match;
        while(match = regex.exec(url)) {
            params[match[1]] = match[2];
        }
        return params;
    }

然后像getParams(url)一样调用它

window.location.href.split("?")

则忽略第一个索引

Array.prototype.slice.call(window.location.href.split("?"), 1) 

返回url参数数组

var paramArray = Array.prototype.slice.call(window.location.href.split(/[?=]+/), 1);
var paramObject = paramArray.reduce(function(x, y, i, a){ (i%2==0) ?  (x[y] = a[i+1]) : void 0; return x; }, {});

paramObject包含映射为js对象的所有参数