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

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

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


当前回答

window.location.search.slice(1).split('&').reduce((res, val) => ({...res, [val.split('=')[0]]: val.split('=')[1]}), {})

其他回答

这个问题的答案太多了,所以我再加一个。

/**
 * parses and returns URI query parameters 
 * 
 * @param {string} param parm
 * @param {bool?} asArray if true, returns an array instead of a scalar 
 * @returns {Object|Array} 
 */
function getURIParameter(param, asArray) {
    return document.location.search.substring(1).split('&').reduce(function(p,c) {
        var parts = c.split('=', 2).map(function(param) { return decodeURIComponent(param); });
        if(parts.length == 0 || parts[0] != param) return (p instanceof Array) && !asArray ? null : p;
        return asArray ? p.concat(parts.concat(true)[1]) : parts.concat(true)[1];
    }, []);
}

用法:

getURIParameter("id")  // returns the last id or null if not present
getURIParameter("id", true) // returns an array of all ids

这将处理空参数(那些没有“=value”的键)、标量和基于数组的值检索API的公开以及正确的URI组件解码。

以下是我的解决方案:jsfiddle

下面的方法返回一个包含给定URL参数的字典。如果没有参数,则为空。

function getParams(url){
    var paramsStart = url.indexOf('?');
    var params = null;

    //no params available
    if(paramsStart != -1){
        var paramsString = url.substring(url.indexOf('?') + 1, url.length);

        //only '?' available
        if(paramsString != ""){
            var paramsPairs = paramsString.split('&');

            //preparing
            params = {};
            var empty = true;
            var index  = 0;
            var key = "";
            var val = "";

            for(i = 0, len = paramsPairs.length; i < len; i++){
                index = paramsPairs[i].indexOf('=');

                //if assignment symbol found
                if(index != -1){
                    key = paramsPairs[i].substring(0, index);
                    val = paramsPairs[i].substring(index + 1, paramsPairs[i].length);

                    if(key != "" && val != ""){

                        //extend here for decoding, integer parsing, whatever...

                        params[key] = val;

                        if(empty){
                            empty = false;
                        }
                    }                    
                }
            }

            if(empty){
                params = null;
            }
        }
    }

    return params;
}

获取单个参数值:

function getQueryParameter(query, parameter) {
return (window.location.href.split(parameter + '=')[1].split('&')[0]);}

PHP parse_str copycat..:)

// Handles also array params well
function parseQueryString(query) {
    var pars = (query != null ? query : "").replace(/&+/g, "&").split('&'),
        par, key, val, re = /^([\w]+)\[(.*)\]/i, ra, ks, ki, i = 0,
        params = {};

    while ((par = pars.shift()) && (par = par.split('=', 2))) {
        key = decodeURIComponent(par[0]);
        // prevent param value going to be "undefined" as string
        val = decodeURIComponent(par[1] || "").replace(/\+/g, " ");
        // check array params
        if (ra = re.exec(key)) {
            ks = ra[1];
            // init array param
            if (!(ks in params)) {
                params[ks] = {};
            }
            // set int key
            ki = (ra[2] != "") ? ra[2] : i++;
            // set array param
            params[ks][ki] = val;
            // go on..
            continue;
        }
        // set param
        params[key] = val;
    }

    return params;
}

var query = 'foo=1&bar=The+bar!%20&arr[]=a0&arr[]=a1&arr[s]=as&isset&arr[]=last';
var params = parseQueryString(query);
console.log(params)
console.log(params.foo)        // 1
console.log(params.bar)        // The bar!
console.log(params.arr[0])     // a0
console.log(params.arr[1])     // a1
console.log(params.arr.s)      // as
console.log(params.arr.none)   // undefined
console.log("isset" in params) // true like: isset($_GET['isset'])



/*
// in php
parse_str('foo=1&bar=The+bar!%20&arr[]=a0&arr[]=a1&arr[s]=as&isset&arr[]=last', $query);
print_r($query);

Array
(
    [foo] => 1
    [bar] => The bar!
    [arr] => Array
        (
            [0] => a0
            [1] => a1
            [s] => as
            [2] => last
        )

    [isset] =>
)*/

对于像index.html这样的单参数值?msg=1使用以下代码,

$(window).load(function(){
    queryString();
});

function queryString()
{
    var queryString = window.location.search.substring(1);
    var varArray = queryString.split("="); //eg. index.html?msg=1

    var param1 = varArray[0];
    var param2 = varArray[1];

}

对于所有参数值,请使用以下代码:,

$(window).load(function(){
    queryString();
});

function queryString()
{
    var queryString = window.location.search;
    var varArray = queryString.split("&");
    for (var i=0;i<varArray.length;i++) {
      var param = varArray[i].split("=");
        //parameter-value pair
    }
}