我有一个带有一些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执行此操作?
当前回答
在我的情况下(重定向到具有所有子url的新域)::
window.location.replace("https://newdomain.com" + window.location.pathname);
其他回答
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对象的所有参数
一个内衬和IE11友好:
> (window.location.href).match('c=([^&]*)')[1]
> "m2-m3-m4-m5"
使用replace()方法的最简单方法:
从urlStr字符串:
paramVal = urlStr.replace(/.*param_name=([^&]*).*|(.*)/, '$1');
或从当前URL:
paramVal = document.URL.replace(/.*param_name=([^&]*).*|(.*)/, '$1');
说明:
document.URL-接口以字符串形式返回文档位置(页面URL)。replace()-方法返回一个新字符串,其中模式的部分或全部匹配项由替换项替换。/.*param_name=([^&]*).*/-括在斜杠之间的正则表达式模式,表示:.*-零个或多个字符,param_name=-已搜索的param名称,正则表达式中的()-组,[^&]*-一个或多个字符,不包括&,|-交替,$1-对正则表达式中第一个组的引用。
var urlStr='www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5’;var c=urlStr.replace(/.*c=([^&]*).*|(.*)/,'$1');var notExisted=urlStr.replace(/.*not_existed=([^&]*).*|(.*)/,'$1');console.log(`c==='${c}');console.log(`notExisted=='${notExisted}');
以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 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')