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

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

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


当前回答

以json形式从window.location中的搜索对象中提取所有url参数

export const getURLParams = location => {
    const searchParams = new URLSearchParams(location.search)
    const params = {}

    for (let key of searchParams.keys()) {
        params[key] = searchParams.get(key)
    }

    return params
}

console.log(getURLParams({ search: '?query=someting&anotherquery=anotherthing' }))

// --> {query: "someting", anotherquery: "anotherthing"}

其他回答

// http:localhost:8080/path?param_1=a&param_2=b
var getParamsMap = function () {
    var params = window.location.search.split("&");
    var paramsMap = {};
    params.forEach(function (p) {
        var v = p.split("=");
        paramsMap[v[0]]=decodeURIComponent(v[1]);
    });
    return paramsMap;
};

// -----------------------

console.log(getParamsMap()["param_1"]);  // should log "a"     

我使用parseUri库。它允许您完全按照您的要求进行操作:

var uri = 'www.test.com/t.html&a=1&b=3&c=m2-m3-m4-m5';
var c = uri.queryKey['c'];
// c = 'm2-m3-m4-m5'

还有一个建议。

已经有一些很好的答案,但我发现它们不必要地复杂,难以理解。这是一个简短、简单的数组,它返回一个简单的关联数组,其中键名与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”。

或者如果您不想重新发明URI解析轮,请使用URI.js

要获取名为foo的参数的值,请执行以下操作:

new URI((''+document.location)).search(true).foo

它的作用是

将document.location转换为字符串(它是一个对象)将该字符串输入到URI.js的URI类构造器调用search()函数以获取url的搜索(查询)部分(传递true告诉它输出一个对象)访问结果对象的foo属性以获取值

这是一把小提琴。。。。http://jsfiddle.net/m6tett01/12/

ECMAScript 6解决方案:

var params = window.location.search
  .substring(1)
  .split("&")
  .map(v => v.split("="))
  .reduce((map, [key, value]) => map.set(key, decodeURIComponent(value)), new Map())