我有一个带有一些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']
其他回答
window.location.search.slice(1).split('&').reduce((res, val) => ({...res, [val.split('=')[0]]: val.split('=')[1]}), {})
使用道场。这里没有其他解决方案是如此简短或经过充分测试的:
require(["dojo/io-query"], function(ioQuery){
var uri = "www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5 ";
var query = uri.substring(uri.indexOf("?") + 1, uri.length);
var queryObject = ioQuery.queryToObject(query);
console.log(queryObject.c); //prints m2-m3-m4-m5
});
从许多答案中学习(如VaMoose的、Gnarf的或Blixt的)。
您可以创建一个对象(或使用Location对象)并添加一个方法,该方法允许您获取URL参数,解码后使用JS样式:
Url = {
params: undefined,
get get(){
if(!this.params){
var vars = {};
if(url.length!==0)
url.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value){
key=decodeURIComponent(key);
if(typeof vars[key]==="undefined") {
vars[key]= decodeURIComponent(value);
}
else {
vars[key]= [].concat(vars[key], decodeURIComponent(value));
}
});
this.params = vars;
}
return this.params;
}
};
这允许只使用Url.get调用该方法。
第一次它将从url中获取对象,下次它将加载保存的对象。
实例
在url中,如?param1=param1Value¶m2=param2Value¶m1=param1Value2,参数的获取方式如下:
Url.get.param1 //["param1Value","param1Value2"]
Url.get.param2 //"param2Value"
function gup() {
var qs = document.location.search;
qs = qs.split('+').join(' ');
var params = {}, tokens, re = /[?&]?([^=]+)=([^&]*)/g;
while (tokens = re.exec(qs))
params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]);
return params;
}
像这样使用
var params = gup()
然后
params.param1
params.param2
优雅、实用的解决方案
让我们创建一个包含URL参数名作为关键字的对象,然后我们可以通过其名称轻松提取参数:
// URL: https://example.com/?test=true&orderId=9381
// Build an object containing key-value pairs
export const queryStringParams = window.location.search
.split('?')[1]
.split('&')
.map(keyValue => keyValue.split('='))
.reduce<QueryStringParams>((params, [key, value]) => {
params[key] = value;
return params;
}, {});
type QueryStringParams = {
[key: string]: string;
};
// Return URL parameter called "orderId"
return queryStringParams.orderId;