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

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

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


当前回答

这是有效的:

function getURLParameter(name) {
  return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [null, ''])[1].replace(/\+/g, '%20')) || null;
}

我没有得到任何其他最好的答案。

其他回答

我使用

function getVal(str) {
    var v = window.location.search.match(new RegExp('(?:[\?\&]'+str+'=)([^&]+)'));
    return v ? v[1] : null;
}

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

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

简化版,已测试

function get(name){
    var r = /[?&]([^=#]+)=([^&#]*)/g,p={},match;
    while(match = r.exec(window.location)) p[match[1]] = match[2];
    return p[name];
}

用法:

var parameter=获取['parameter']

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

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, "\\$&"));
}
window.location.search.slice(1).split('&').reduce((res, val) => ({...res, [val.split('=')[0]]: val.split('=')[1]}), {})