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

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

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


当前回答

我尽可能喜欢速记:

网址:example.com/mortgage_calc.htm?pmts=120&intr=6.8&prin=10000

香草Javascript:

for ( var vObj = {}, i=0, vArr = window.location.search.substring(1).split('&');
        i < vArr.length; v = vArr[i++].split('='), vObj[v[0]] = v[1] ){}
// vObj = {pmts: "120", intr: "6.8", prin: "10000"}

其他回答

下面是一个获取单个参数的简单函数:

function getUrlParam(paramName) {
    var match = window.location.search.match("[?&]" + paramName + "(?:&|$|=([^&]*))");
    return match ? (match[1] ? decodeURIComponent(match[1]) : "") : null;
}

这些特殊情况的处理与URLSearchParams一致:

如果缺少参数,则返回null。如果参数存在但没有“=”(例如“?param”),则返回“”。

笔记如果参数名称可能包含特殊的URL或正则字符(例如,如果它来自用户输入),则需要对其进行转义

function getUrlParamWithSpecialName(paramName) {
    return getUrlParam(encodeURIComponent(paramName).replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
}
function parseUrl(url){
    let urlParam = url.split("?")[1];
    console.log("---------> URL param : " + urlParam);
    urlParam = urlParam.split("&");
    let urlParamObject = {};
    for(let i=0;i < urlParam.length;i++){
        let tmp = urlParam[i].split("=");
        urlParamObject[tmp[0]] = tmp[1];
    }
    return urlParamObject;
}

let param = parseUrl(url);
param.a // output 10
param.b // output 20

来源

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')

获取单个参数值:

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

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

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