本文翻译自:Parse query string in JavaScript [duplicate]
Possible Duplicate: 可能重复:
How can I get query string values? 如何获取查询字符串值?
I need to parse the query string www.mysite.com/default.aspx?dest=aboutus.aspx
. 我需要解析查询字符串www.mysite.com/default.aspx?dest=aboutus.aspx
。 How do I get the dest
variable in JavaScript? 如何在JavaScript中获取dest
变量?
参考:https://stackoom.com/question/8lqZ/在JavaScript中解析查询字符串-重复
function parseQuery(queryString) {
var query = {};
var pairs = (queryString[0] === '?' ? queryString.substr(1) : queryString).split('&');
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i].split('=');
query[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1] || '');
}
return query;
}
Turns query string like hello=1&another=2
into object {hello: 1, another: 2}
. 将查询字符串(如hello=1&another=2
转换为对象{hello: 1, another: 2}
。 From there, it's easy to extract the variable you need. 从那里,很容易提取您需要的变量。
That said, it does not deal with array cases such as "hello=1&hello=2&hello=3"
. 也就是说,它不处理诸如"hello=1&hello=2&hello=3"
数组情况。 To work with this, you must check whether a property of the object you make exists before adding to it, and turn the value of it into an array, pushing any additional bits. 要使用它,您必须在添加之前检查您所创建的对象的属性是否存在,并将其值转换为数组,并推送任何其他位。
I wanted to pick up specific links within a DOM element on a page, send those users to a redirect page on a timer and then pass them onto the original clicked URL. 我想拿起一个页面上的DOM元素中的 特定环节,把那些用户重定向页面上的计时器,然后将它们传递给原始广告点击的网址。 This is how I did it using regular javascript incorporating one of the methods above. 这就是我使用常规javascript结合上述方法之一的方法。
Page with links: Head 带链接的页面: Head
function replaceLinks() {
var content = document.getElementById('mainContent');
var nodes = content.getElementsByTagName('a');
for (var i = 0; i < document.getElementsByTagName('a').length; i++) {
{
href = nodes[i].href;
if (href.indexOf("thisurl.com") != -1) {
nodes[i].href="http://www.thisurl.com/redirect.aspx" + "?url=" + nodes[i];
nodes[i].target="_blank";
}
}
}
}
Body 身体
Redirect page Head 重定向页面 头部
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
if (decodeURIComponent(pair[0]) == variable) {
return decodeURIComponent(pair[1]);
}
}
console.log('Query variable %s not found', variable);
}
function delayer(){
window.location = getQueryVariable('url')
}
Body 身体
Following on from my comment to the answer @bobby posted, here is the code I would use: 继我对@bobby发布的答案的评论之后,这里是我将使用的代码:
function parseQuery(str)
{
if(typeof str != "string" || str.length == 0) return {};
var s = str.split("&");
var s_length = s.length;
var bit, query = {}, first, second;
for(var i = 0; i < s_length; i++)
{
bit = s[i].split("=");
first = decodeURIComponent(bit[0]);
if(first.length == 0) continue;
second = decodeURIComponent(bit[1]);
if(typeof query[first] == "undefined") query[first] = second;
else if(query[first] instanceof Array) query[first].push(second);
else query[first] = [query[first], second];
}
return query;
}
This code takes in the querystring provided (as 'str') and returns an object. 此代码接受提供的查询字符串(作为'str')并返回一个对象。 The string is split on all occurances of &, resulting in an array. 字符串在&的所有出现时被拆分,从而产生一个数组。 the array is then travsersed and each item in it is split by "=". 然后对该数组进行travsers,并将其中的每个项目拆分为“=”。 This results in sub arrays wherein the 0th element is the parameter and the 1st element is the value (or undefined if no = sign). 这导致子数组,其中第0个元素是参数,第1个元素是值(如果没有=符号,则为undefined)。 These are mapped to object properties, so for example the string "hello=1&another=2&something" is turned into: 这些映射到对象属性,因此例如字符串“hello = 1&another = 2&something”变为:
{
hello: "1",
another: "2",
something: undefined
}
In addition, this code notices repeating reoccurances such as "hello=1&hello=2" and converts the result into an array, eg: 此外,此代码注意到重复重复,例如“hello = 1&hello = 2”并将结果转换为数组,例如:
{
hello: ["1", "2"]
}
You'll also notice it deals with cases in whih the = sign is not used. 你还会注意到它处理了没有使用=符号的情况。 It also ignores if there is an equal sign straight after an & symbol. 如果在&符号后面有一个等号,它也会忽略它。
A bit overkill for the original question, but a reusable solution if you ever need to work with querystrings in javascript :) 对于原始问题有点矫枉过正,但如果您需要在javascript中使用查询字符串,则可以使用可重用的解决方案:)
I wanted a simple function that took a URL as an input and returned a map of the query params. 我想要一个简单的函数,它将URL作为输入并返回查询参数的映射。 If I were to improve this function, I would support the standard for array data in the URL, and or nested variables. 如果我要改进这个功能,我会支持URL和/或嵌套变量中的数组数据标准。
This should work back and for with the jQuery.param( qparams ) function. 这应该可以使用jQuery.param(qparams)函数。
function getQueryParams(url){
var qparams = {},
parts = (url||'').split('?'),
qparts, qpart,
i=0;
if(parts.length <= 1 ){
return qparams;
}else{
qparts = parts[1].split('&');
for(i in qparts){
qpart = qparts[i].split('=');
qparams[decodeURIComponent(qpart[0])] =
decodeURIComponent(qpart[1] || '');
}
}
return qparams;
};
Me too! 我也是! http://jsfiddle.net/drzaus/8EE8k/ http://jsfiddle.net/drzaus/8EE8k/
(Note: without fancy nested or duplicate checking) (注意:没有花哨的嵌套或重复检查)
deparam = function (querystring) {
// remove any preceding url and split
querystring = querystring.substring(querystring.indexOf('?')+1).split('&');
var params = {}, pair, d = decodeURIComponent;
// march and parse
for (var i = querystring.length - 1; i >= 0; i--) {
pair = querystring[i].split('=');
params[d(pair[0])] = d(pair[1] || '');
}
return params;
};//-- fn deparam
And tests: 并测试:
var tests = {};
tests["simple params"] = "ID=2&first=1&second=b";
tests["full url"] = "http://blah.com/?" + tests["simple params"];
tests['just ?'] = '?' + tests['simple params'];
var $output = document.getElementById('output');
function output(msg) {
$output.innerHTML += "\n" + Array.prototype.slice.call(arguments, 0).join("\n");
}
$.each(tests, function(msg, test) {
var q = deparam(test);
// prompt, querystring, result, reverse
output(msg, test, JSON.stringify(q), $.param(q));
output('-------------------');
});
Results in: 结果是:
simple params
ID=2&first=1&second=b
{"second":"b","first":"1","ID":"2"}
second=b&first=1&ID=2
-------------------
full url
http://blah.com/?ID=2&first=1&second=b
{"second":"b","first":"1","ID":"2"}
second=b&first=1&ID=2
-------------------
just ?
?ID=2&first=1&second=b
{"second":"b","first":"1","ID":"2"}
second=b&first=1&ID=2
-------------------