我有一个带有一些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();

其他回答

我使用

function getVal(str) {
    var v = window.location.search.match(new RegExp('(?:[\?\&]'+str+'=)([^&]+)'));
    return v ? v[1] : null;
}

您可以运行此函数

    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;
    }

    var source = getUrlVars()["lm_supplier"];
    var el = source.toString();
    var result= decodeURI(el);

console.log(result)

该函数从url获取所需内容,var source=getUrlVars()[“从url中输入您想要的内容”];

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

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

以下是我所做的:

var uriParams = getSearchParameters();
alert(uriParams.c);


// background functions:

// Get object/associative array of URL parameters
function getSearchParameters () {
  var prmstr = window.location.search.substr(1);
  return prmstr !== null && prmstr !== "" ? transformToAssocArray(prmstr) : {};
}

// convert parameters from url-style string to associative array
function transformToAssocArray (prmstr) {
  var params = {},
      prmarr = prmstr.split("&");

  for (var i = 0; i < prmarr.length; i++) {
    var tmparr = prmarr[i].split("=");
    params[tmparr[0]] = tmparr[1];
  }
  return params;
}

我更喜欢使用可用的资源,而不是重新设计如何解析这些参数。

将URL解析为对象提取搜索参数部分将searchParams从迭代器转换为具有数组扩展的数组。将键值数组缩减为一个对象。

常量url='http://www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5';const params=[…新URL(URL).searchParams.entries()].reduce((a,c)=>对象.assign(a,{[c[0]]:c[1]}),{})console.log(参数);