我有一个带有一些GET参数的URL,如下所示:
www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5
我需要得到c的全部值。我试图读取URL,但只得到m2。如何使用JavaScript执行此操作?
我有一个带有一些GET参数的URL,如下所示:
www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5
我需要得到c的全部值。我试图读取URL,但只得到m2。如何使用JavaScript执行此操作?
当前回答
简化版,已测试
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']
其他回答
// Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
// Usage for URL: http://my.site.com/location?locationId=53cc272c0364aefcb78756cd&shared=false
var id = getUrlVars()["locationId"];
从这里得到:http://jquery-howto.blogspot.ru/2009/09/get-url-parameters-values-with-jquery.html
这是一种只检查一个参数的简单方法:
示例URL:
http://myserver/action?myParam=2
Javascript示例:
var myParam = location.search.split('myParam=')[1]
如果URL中存在“myParam”。。。变量myParam将包含“2”,否则将未定义。
在这种情况下,可能需要一个默认值:
var myParam = location.search.split('myParam=')[1] ? location.search.split('myParam=')[1] : 'myDefaultValue';
更新:这更有效:
var url = "http://www.example.com/index.php?myParam=384&login=admin"; // or window.location.href for current url
var captured = /myParam=([^&]+)/.exec(url)[1]; // Value is in [1] ('384' in our case)
var result = captured ? captured : 'myDefaultValue';
即使URL中充满了参数,它也能正常工作。
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] 从匹配数组中选择第一组
这是有效的:
function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [null, ''])[1].replace(/\+/g, '%20')) || null;
}
我没有得到任何其他最好的答案。
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