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

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

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


当前回答

您可以添加一个输入框,然后要求用户将值复制到其中……这非常简单:

<h1>Hey User! Can you please copy the value out of the location bar where it says like, &m=2? Thanks! And then, if you could...paste it in the box below and click the Done button?</h1>
<input type='text' id='the-url-value' />
<input type='button' value='This is the Done button. Click here after you do all that other stuff I wrote.' />

<script>
//...read the value on click

好吧,但说真的。。。我发现了这段代码,它似乎很有用:

http://www.developerdrive.com/2013/08/turning-the-querystring-into-a-json-object-using-javascript/

function queryToJSON() {
    var pairs = location.search.slice(1).split('&');

    var result = {};
    pairs.forEach(function(pair) {
        pair = pair.split('=');
        result[pair[0]] = decodeURIComponent(pair[1] || '');
    });

    return JSON.parse(JSON.stringify(result));
}

var query = queryToJSON();

其他回答

您可以在location.search中获取查询字符串,然后可以分割问号后的所有内容:

var params = {};

if (location.search) {
    var parts = location.search.substring(1).split('&');

    for (var i = 0; i < parts.length; i++) {
        var nv = parts[i].split('=');
        if (!nv[0]) continue;
        params[nv[0]] = nv[1] || true;
    }
}

// Now you can get the parameters you want like so:
var abc = params.abc;
// 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"     

在我的情况下(重定向到具有所有子url的新域)::

window.location.replace("https://newdomain.com" + window.location.pathname);

一个内衬和IE11友好:

> (window.location.href).match('c=([^&]*)')[1]
> "m2-m3-m4-m5"

简单的方法

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

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