我需要解析查询字符串www.mysite.com/default.aspx?dest=aboutus.aspx。 如何在JavaScript中获得dest变量?
当前回答
以下是我对@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中使用查询字符串,这是一个可重用的解决方案:)
其他回答
如果你知道你将只有一个查询字符串变量,你可以简单地做:
var dest = location.search.replace(/^.*?\=/, '');
下面是一个快速简单的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'));
你也可以使用Rodney Rehm的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 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'));
干杯
下面是我的版本,基于上面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);