在JavaScript中,如何获取URL字符串的参数(而不是当前URL)?
例如:
www.domain.com/?v=123&p=hello
我能否在 JSON 对象中获取“v”和“p”?
在JavaScript中,如何获取URL字符串的参数(而不是当前URL)?
例如:
www.domain.com/?v=123&p=hello
我能否在 JSON 对象中获取“v”和“p”?
问题提出2.5年后,您可以安全地使用Array.forEach
。正如@ricosrealm所建议的那样,在此函数中使用了decodeURIComponent
。
function getJsonFromUrl(url) {
if(!url) url = location.search;
var query = url.substr(1);
var result = {};
query.split("&").forEach(function(part) {
var item = part.split("=");
result[item[0]] = decodeURIComponent(item[1]);
});
return result;
}
其实这并不简单,请查看评论中的同行评审,特别是:
=
(@AndrewF)+
(由我添加)也许这应该提交到codereview SE,但在这里更安全且无需正则表达式的代码:
function getSearchOrHashBased(url) {
if(!url) url = location.href;
var question = url.indexOf("?");
var hash = url.indexOf("#");
if(hash==-1 && question==-1) return {};
if(hash==-1) hash = url.length;
return question==-1 || hash==question+1
? url.substring(hash)
: url.substring(question+1, hash);
}
// use query = getSearchOrHashBased(location.href)
// or query = location.search.substring(1)
function getJsonFromUrl(query) {
var result = {};
query.split("&").forEach(function(part) {
if(!part) return;
part = part.split("+").join(" "); // + to space, regexp-free version
var eq = part.indexOf("=");
var key = eq>-1 ? part.substr(0,eq) : part;
var val = eq>-1 ? decodeURIComponent(part.substr(eq+1)) : "";
var from = key.indexOf("[");
if(from==-1) result[decodeURIComponent(key)] = val;
else {
var to = key.indexOf("]",from);
var index = decodeURIComponent(key.substring(from+1,to));
key = decodeURIComponent(key.substring(0,from));
if(!result[key]) result[key] = [];
if(!index) result[key].push(val);
else result[key][index] = val;
}
});
return result;
}
这个函数甚至可以解析像URL一样的内容
var url = "?foo%20e[]=a%20a&foo+e[%5Bx%5D]=b&foo e[]=c";
// {"foo e": ["a a", "c", "[x]":"b"]}
var obj = getJsonFromUrl(url)["foo e"];
for(var key in obj) { // Array.forEach would skip string keys here
console.log(key,":",obj[key]);
}
/*
0 : a a
1 : c
[x] : b
*/
问题提出后的7年,该功能被标准化为URLSearchParams,再过4年,通过Proxy可以进一步简化访问,如this answer中所解释的那样。然而,新的功能无法解析上述示例网址。
location.search
在基于哈希的路由中无法工作:http://localhost:9000/#/documents?lang=es
将为 location.search
返回一个空字符串。您需要使用 location.hash
或 location.href
。 - cmfolioresult[decodeURIComponent(item[0])] = decodeURIComponent(item[1]);
而不是result[item[0]] = decodeURIComponent(item[1]);
。 - AndrewFsplit("=")
将无法处理包含未编码的=的参数值,这虽然不常见但确实会发生。我建议使用正则表达式,这样您可以在保持简洁的同时获得更好的逻辑。 - AndrewFgenre=R&B&name=John
这样的字符串,它们无法被正确解析。在拆分字符串并知道什么是键和什么是值之后,您需要进行解码,方括号作为“key in keys”在这里需要特别注意,参见代码。 - Jan Turoň你可以使用以下代码获得包含这些参数的JavaScript对象:
var regex = /[?&]([^=#]+)=([^&#]*)/g,
url = window.location.href,
params = {},
match;
while(match = regex.exec(url)) {
params[match[1]] = match[2];
}
正则表达式很可能可以得到改进。它只是查找由=
字符分隔的名称-值对,并且由&
字符(或=
字符用于第一个)分隔的自身成对。对于您的示例,上述内容将导致:
{v: "123", p: "hello"}
getParameter
的文档在哪里? - James Allardice[^=#&]+
而不仅是[^=#]+
,因为没有值的名称是合法和常见的。同时确保对名称和值进行解码:params [decodeURIComponent(match [1])] = decodeURIComponent(match [2]);
。 - AndrewF
URLSearchParams
对象的好答案。另请参阅MDN的文档页面。也支持polyfill。 - alttagnew URL("http://www.example.com/?v=123&p=hello").searchParams.toString().split("&").reduce((previous, current)=> { const [key, value] = current.split("="); previous[key] = value; return previous },{})
- Flavien VolkenURLSearchParams
API是首选,但要注意IE的缺乏支持:https://caniuse.com/#search=URL - Chris Hayes