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

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

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


当前回答

我一次又一次遇到同样的问题。现在这里的许多用户现在我以我的HAX工作而闻名,

所以我用以下方法来解决:

PHP:

echo "<p style="display:none" id=\"hidden-GET\">".$_GET['id']."</p>";

JS:

document.getElementById("hidden-GET").innerHTML;

简单的HAX但有效。

其他回答

从许多答案中学习(如VaMoose的、Gnarf的或Blixt的)。

您可以创建一个对象(或使用Location对象)并添加一个方法,该方法允许您获取URL参数,解码后使用JS样式:

Url = {
    params: undefined,
    get get(){
        if(!this.params){
            var vars = {};
            if(url.length!==0)
                url.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value){
                    key=decodeURIComponent(key);
                    if(typeof vars[key]==="undefined") {
                        vars[key]= decodeURIComponent(value);
                    }
                    else {
                        vars[key]= [].concat(vars[key], decodeURIComponent(value));
                    }
                });
            this.params = vars;
        }
        return this.params;
    }
};

这允许只使用Url.get调用该方法。

第一次它将从url中获取对象,下次它将加载保存的对象。

实例

在url中,如?param1=param1Value&param2=param2Value&param1=param1Value2,参数的获取方式如下:

Url.get.param1 //["param1Value","param1Value2"]
Url.get.param2 //"param2Value"

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

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

一个内衬和IE11友好:

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

来源

function gup( name, url ) {
    if (!url) url = location.href;
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp( regexS );
    var results = regex.exec( url );
    return results == null ? null : results[1];
}
gup('q', 'hxxp://example.com/?q=abc')

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] 从匹配数组中选择第一组