我有一个带有一些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执行此操作?
当前回答
以json形式从window.location中的搜索对象中提取所有url参数
export const getURLParams = location => {
const searchParams = new URLSearchParams(location.search)
const params = {}
for (let key of searchParams.keys()) {
params[key] = searchParams.get(key)
}
return params
}
console.log(getURLParams({ search: '?query=someting&anotherquery=anotherthing' }))
// --> {query: "someting", anotherquery: "anotherthing"}
其他回答
window.location.href.split("?")
则忽略第一个索引
Array.prototype.slice.call(window.location.href.split("?"), 1)
返回url参数数组
var paramArray = Array.prototype.slice.call(window.location.href.split(/[?=]+/), 1);
var paramObject = paramArray.reduce(function(x, y, i, a){ (i%2==0) ? (x[y] = a[i+1]) : void 0; return x; }, {});
paramObject包含映射为js对象的所有参数
以json形式从window.location中的搜索对象中提取所有url参数
export const getURLParams = location => {
const searchParams = new URLSearchParams(location.search)
const params = {}
for (let key of searchParams.keys()) {
params[key] = searchParams.get(key)
}
return params
}
console.log(getURLParams({ search: '?query=someting&anotherquery=anotherthing' }))
// --> {query: "someting", anotherquery: "anotherthing"}
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
ECMAScript 6解决方案:
var params = window.location.search
.substring(1)
.split("&")
.map(v => v.split("="))
.reduce((map, [key, value]) => map.set(key, decodeURIComponent(value)), new Map())
我使用
function getVal(str) {
var v = window.location.search.match(new RegExp('(?:[\?\&]'+str+'=)([^&]+)'));
return v ? v[1] : null;
}