用JavaScript解析查询字符串

我需要解析查询字符串www.mysite.com/default.aspx?dest=aboutus.aspx。 我如何在JavaScript中获得dest变量?< / p >
557112 次浏览

下面是一个快速简单的JavaScript查询字符串解析方法:

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);
}

现在向page.html吗?x =你好发出一个请求:

console.log(getQueryVariable('x'));

如果你知道你将只有一个查询字符串变量,你可以简单地做:

var dest = location.search.replace(/^.*?\=/, '');

下面的函数将用正则表达式解析搜索字符串,缓存结果并返回所请求变量的值:

window.getSearch = function(variable) {
var parsedSearch;
parsedSearch = window.parsedSearch || (function() {
var match, re, ret;
re = /\??(.*?)=([^\&]*)&?/gi;
ret = {};
while (match = re.exec(document.location.search)) {
ret[match[1]] = match[2];
}
return window.parsedSearch = ret;
})();
return parsedSearch[variable];
};
你可以不带任何参数调用它一次并使用window.parsedSearch对象,也可以随后调用getSearch。 我还没有完全测试这个,正则表达式可能仍然需要一些调整

下面是我的版本,基于上面Braceyard的版本,但解析为“字典”,并支持没有“=”的搜索参数。在JQuery $(document).ready()函数中使用它。参数以键/值对的形式存储在argsParsed中,你可能想保存在某个地方…

'use strict';


function parseQuery(search) {


var args = search.substring(1).split('&');


var argsParsed = {};


var i, arg, kvp, key, value;


for (i=0; i < args.length; i++) {


arg = args[i];


if (-1 === arg.indexOf('=')) {


argsParsed[decodeURIComponent(arg).trim()] = true;
}
else {


kvp = arg.split('=');


key = decodeURIComponent(kvp[0]).trim();


value = decodeURIComponent(kvp[1]).trim();


argsParsed[key] = value;
}
}


return argsParsed;
}


parseQuery(document.location.search);

这个怎么样?

function getQueryVar(varName){
// Grab and unescape the query string - appending an '&' keeps the RegExp simple
// for the sake of this example.
var queryStr = unescape(window.location.search) + '&';


// Dynamic replacement RegExp
var regex = new RegExp('.*?[&\\?]' + varName + '=(.*?)&.*');


// Apply RegExp to the query string
var val = queryStr.replace(regex, "$1");


// If the string is the same, we didn't find a match - return false
return val == queryStr ? false : val;
}

..然后用:

alert('Var "dest" = ' + getQueryVar('dest'));

干杯

你也可以通过罗德尼·雷姆曾为此写过使用优秀的URI.js库。方法如下:-

var qs = URI('www.mysite.com/default.aspx?dest=aboutus.aspx').query(true); // == { dest : 'aboutus.aspx' }
alert(qs.dest); // == aboutus.aspx

解析当前页面的查询字符串:-

var $_GET = URI(document.URL).query(true); // ala PHP
alert($_GET['dest']); // == aboutus.aspx
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;
}

将类似hello=1&another=2的查询字符串转换为对象{hello: 1, another: 2}。从那里,很容易提取所需的变量。

也就是说,它不处理像"hello=1&hello=2&hello=3"这样的数组情况。要使用这种方法,必须在添加之前检查所创建对象的属性是否存在,并将其值转换为数组,将任何额外的位压入。

我想在页面上获得具体的链接一个DOM元素,将这些用户发送到计时器上的重定向页面,然后将它们传递到原始点击的URL。这就是我如何使用常规javascript结合上面的方法之一。

网页附有连结:

  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 onload="replaceLinks()">

< >强重定向页面 头< / em >

   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 onload="setTimeout('delayer()', 1000)">

以下是我对@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;
}

这段代码接受所提供的查询字符串(作为'str')并返回一个对象。字符串在出现&时被拆分,从而生成数组。然后遍历数组,其中的每一项都用“=”分隔。这将导致子数组,其中第0个元素是参数,第1个元素是值(如果no =符号则为undefined)。它们被映射到对象属性,例如字符串"hello=1&another=2&something"被转换为:

{
hello: "1",
another: "2",
something: undefined
}

此外,这段代码注意到重复出现,如“hello=1&hello=2”,并将结果转换为一个数组,例如:

{
hello: ["1", "2"]
}

您还会注意到它处理不使用=符号的情况。它也忽略了&后面是否有等号;的象征。

对于最初的问题有点过度,但如果你需要在javascript中使用查询字符串,这是一个可重用的解决方案:)

我想要一个简单的函数,以URL作为输入,并返回查询参数的映射。 如果我要改进这个函数,我将支持URL中数组数据的标准,和或嵌套变量。< / p >

这应该可以用于jQuery。参数(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;
};

我也是!http://jsfiddle.net/drzaus/8EE8k/

(注:无花哨嵌套或重复检查)

deparam = (function(d,x,params,p,i,j) {
return function (qs) {
// start bucket; can't cheat by setting it in scope declaration or it overwrites
params = {};
// remove preceding non-querystring, correct spaces, and split
qs = qs.substring(qs.indexOf('?')+1).replace(x,' ').split('&');
// march and parse
for (i = qs.length; i > 0;) {
p = qs[--i];
// allow equals in value
j = p.indexOf('=');
// what if no val?
if(j === -1) params[d(p)] = undefined;
else params[d(p.substring(0,j))] = d(p.substring(j+1));
}


return params;
};//--  fn  deparam
})(decodeURIComponent, /\+/g);

和测试:

var tests = {};
tests["simple params"] = "ID=2&first=1&second=b";
tests["full url"] = "http://blah.com/?third=c&fourth=d&fifth=e";
tests['just ?'] = '?animal=bear&fruit=apple&building=Empire State Building&spaces=these+are+pluses';
tests['with equals'] = 'foo=bar&baz=quux&equals=with=extra=equals&grault=garply';
tests['no value'] = 'foo=bar&baz=&qux=quux';
tests['value omit'] = 'foo=bar&baz&qux=quux';


var $output = document.getElementById('output');
function output(msg) {
msg = Array.prototype.slice.call(arguments, 0).join("\n");
if($output) $output.innerHTML += "\n" + msg + "\n";
else console.log(msg);
}
var results = {}; // save results, so we can confirm we're not incorrectly referencing
$.each(tests, function(msg, test) {
var q = deparam(test);
results[msg] = q;
output(msg, test, JSON.stringify(q), $.param(q));
output('-------------------');
});


output('=== confirming results non-overwrite ===');
$.each(results, function(msg, result) {
output(msg, JSON.stringify(result));
output('-------------------');
});

结果:

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/?third=c&fourth=d&fifth=e
{"fifth":"e","fourth":"d","third":"c"}
fifth=e&fourth=d&third=c
-------------------
just ?
?animal=bear&fruit=apple&building=Empire State Building&spaces=these+are+pluses
{"spaces":"these are pluses","building":"Empire State Building","fruit":"apple","animal":"bear"}
spaces=these%20are%20pluses&building=Empire%20State%20Building&fruit=apple&animal=bear
-------------------
with equals
foo=bar&baz=quux&equals=with=extra=equals&grault=garply
{"grault":"garply","equals":"with=extra=equals","baz":"quux","foo":"bar"}
grault=garply&equals=with%3Dextra%3Dequals&baz=quux&foo=bar
-------------------
no value
foo=bar&baz=&qux=quux
{"qux":"quux","baz":"","foo":"bar"}
qux=quux&baz=&foo=bar
-------------------
value omit
foo=bar&baz&qux=quux
{"qux":"quux","foo":"bar"}   <-- it's there, i swear!
qux=quux&baz=&foo=bar        <-- ...see, jQuery found it
-------------------