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

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

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


当前回答

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

/**
 * 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组件解码。

其他回答

简单的方法

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

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

$_GET: function (param) {
    var regex = new RegExp("(?:[?&]+" + param + "=)([^&]*)?", "i");
    var match = regex.exec(window.location.href);
    return match === null ? match : match[1];
}

浏览器供应商已经通过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。

一个内衬和IE11友好:

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

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

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