我有一个带有一些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执行此操作?
当前回答
这里是一个递归解决方案,它没有正则表达式,并且具有最小的变异(只有params对象被变异,我认为这在JS中是不可避免的)。
太棒了,因为它:
是递归的处理多个同名参数处理格式错误的参数字符串(缺少值等)如果“=”在值中,则不中断执行URL解码最后,这太棒了,因为它……啊!!!
代码:
var get_params = function(search_string) {
var parse = function(params, pairs) {
var pair = pairs[0];
var parts = pair.split('=');
var key = decodeURIComponent(parts[0]);
var value = decodeURIComponent(parts.slice(1).join('='));
// Handle multiple parameters of the same name
if (typeof params[key] === "undefined") {
params[key] = value;
} else {
params[key] = [].concat(params[key], value);
}
return pairs.length == 1 ? params : parse(params, pairs.slice(1))
}
// Get rid of leading ?
return search_string.length == 0 ? {} : parse({}, search_string.substr(1).split('&'));
}
var params = get_params(location.search);
// Finally, to get the param you want
params['c'];
其他回答
您可以添加一个输入框,然后要求用户将值复制到其中……这非常简单:
<h1>Hey User! Can you please copy the value out of the location bar where it says like, &m=2? Thanks! And then, if you could...paste it in the box below and click the Done button?</h1>
<input type='text' id='the-url-value' />
<input type='button' value='This is the Done button. Click here after you do all that other stuff I wrote.' />
<script>
//...read the value on click
好吧,但说真的。。。我发现了这段代码,它似乎很有用:
http://www.developerdrive.com/2013/08/turning-the-querystring-into-a-json-object-using-javascript/
function queryToJSON() {
var pairs = location.search.slice(1).split('&');
var result = {};
pairs.forEach(function(pair) {
pair = pair.split('=');
result[pair[0]] = decodeURIComponent(pair[1] || '');
});
return JSON.parse(JSON.stringify(result));
}
var query = queryToJSON();
window.location.search.slice(1).split('&').reduce((res, val) => ({...res, [val.split('=')[0]]: val.split('=')[1]}), {})
// http:localhost:8080/path?param_1=a¶m_2=b
var getParamsMap = function () {
var params = window.location.search.split("&");
var paramsMap = {};
params.forEach(function (p) {
var v = p.split("=");
paramsMap[v[0]]=decodeURIComponent(v[1]);
});
return paramsMap;
};
// -----------------------
console.log(getParamsMap()["param_1"]); // should log "a"
在我的情况下(重定向到具有所有子url的新域)::
window.location.replace("https://newdomain.com" + window.location.pathname);
我开发了一个JavaScript工具,只需一个简单的步骤
首先,将此脚本链接复制到HTML的头部:
<script src="https://booligoosh.github.io/urlParams/urlParams.js"></script>
然后简单地使用urlParams.c或urlParams['c']获取c的值。易于理解的
您可以在这里看到使用您的值的真实演示。
还要记住,我确实开发了这个,但这是一个轻松轻松的解决方案。该工具还包括十六进制字符解码,这通常很有用。