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

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

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


当前回答

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

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

其他回答

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

<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 getUrlVars() {
    var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,    
    function(m,key,value) {
      vars[key] = value;
    });
    return vars;
  }

然后这样称呼:

var fType = getUrlVars()["type"];
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对象的所有参数

简单的方法

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

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

使用replace()方法的最简单方法:

从urlStr字符串:

paramVal = urlStr.replace(/.*param_name=([^&]*).*|(.*)/, '$1');

或从当前URL:

paramVal = document.URL.replace(/.*param_name=([^&]*).*|(.*)/, '$1');

说明:

document.URL-接口以字符串形式返回文档位置(页面URL)。replace()-方法返回一个新字符串,其中模式的部分或全部匹配项由替换项替换。/.*param_name=([^&]*).*/-括在斜杠之间的正则表达式模式,表示:.*-零个或多个字符,param_name=-已搜索的param名称,正则表达式中的()-组,[^&]*-一个或多个字符,不包括&,|-交替,$1-对正则表达式中第一个组的引用。

var urlStr='www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5’;var c=urlStr.replace(/.*c=([^&]*).*|(.*)/,'$1');var notExisted=urlStr.replace(/.*not_existed=([^&]*).*|(.*)/,'$1');console.log(`c==='${c}');console.log(`notExisted=='${notExisted}');