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

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

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


当前回答

function getParamValue(param) {
    var urlParamString = location.search.split(param + "=");
    if (urlParamString.length <= 1) return "";
    else {
        var tmp = urlParamString[1].split("&");
        return tmp[0];
    }
}

无论参数是否为最后一个,这都适用于您的情况。

其他回答

浏览器供应商已经通过URL和URLSearchParams实现了一种本地方式。

let url = new URL('http://www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5');
let searchParams = new URLSearchParams(url.search);
console.log(searchParams.get('c'));  // outputs "m2-m3-m4-m5"

目前支持Firefox、Opera、Safari、Chrome和Edge。有关浏览器支持的列表,请参阅此处。

https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParamshttps://developer.mozilla.org/en-US/docs/Web/API/URL/URL

https://url.spec.whatwg.org/

谷歌工程师埃里克·比德尔曼(Eric Bidelman)建议在不受支持的浏览器上使用这种polyfill。

这是一个我觉得更可读的解决方案,但它需要一个.forEach()填充程序,用于<IE8:

var getParams = function () {
  var params = {};
  if (location.search) {
    var parts = location.search.slice(1).split('&');

    parts.forEach(function (part) {
      var pair = part.split('=');
      pair[0] = decodeURIComponent(pair[0]);
      pair[1] = decodeURIComponent(pair[1]);
      params[pair[0]] = (pair[1] !== 'undefined') ?
        pair[1] : true;
    });
  }
  return params;
}

我在这里举了一个例子。但它在jQuery中。希望它能帮助其他人:

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.url.js"></script>

<!-- URL:  www.example.com/correct/?message=done&year=1990-->

<script type="text/javascript">
$(function(){
    $.url.attr('protocol')  // --> Protocol: "http"
    $.url.attr('path')          // --> host: "www.example.com"
    $.url.attr('query')         // --> path: "/correct/"
    $.url.attr('message')   // --> query: "done"
    $.url.attr('year')      // --> query: "1990"
});
</script>

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

<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();

Try

url.match(/[?&]c=([^&]*)/)[1]

var url=“www.test.com/t.html?a=1&bc=3&c=m2-m3-m4-5”;c=url.match(/[?&]c=([^&]*)/)[1];控制台日志(c);

这是丹尼尔·索科洛夫斯基19年6月27日回答的改进。Regexp解释

[?&]第一个匹配的字符必须是?或&(省略ac=等参数)c=参数名称,结尾为=char(…)第一组匹配[^&]*零个或多个字符(*)不同于(^)&[1] 从匹配数组中选择第一组