解析JavaScript中的查询字符串[重复]

2020/09/30 19:21 · javascript ·  · 0评论

我需要解析查询字符串www.mysite.com/default.aspx?dest=aboutus.aspx如何dest在JavaScript中获取变量?

这是在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 = Hello发出请求

console.log(getQueryVariable('x'));
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转换成object {hello: 1, another: 2}从那里,很容易提取所需的变量。

也就是说,它不处理诸如的数组情况"hello=1&hello=2&hello=3"要使用此功能,必须在添加对象之前检查所创建对象的属性是否存在,并将其值转换为数组,并压入其他任何位。

您还可以使用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 

我也是!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
-------------------

这是我的版本,其松散地基于上述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);

在我对发布的答案@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个元素是值(如果没有=符号,则为未定义)。这些映射到对象属性,因此例如字符串“ hello = 1&another = 2&something”被转换为:

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

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

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

您还会注意到,它处理的情况是不使用=符号。它还会忽略在&符号之后是否有等号。

原始问题有点矫kill过正,但是如果您需要在javascript中使用querystrings,那么可以重用的解决方案:)

如果知道只有一个querystring变量,则可以简单地执行以下操作:

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随后调用我尚未对此进行全面测试,正则表达式可能仍需要进行一些调整...

这个怎么样?

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

干杯

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

这应该可以和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;
};

我想获取页面上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()">

重定向页面

   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)">
本文地址:http://javascript.askforanswer.com/jiexijavascriptzhongdechaxunzifuchuanzhongfu.html
文章标签: ,   ,  
版权声明:本文为原创文章,版权归 javascript 所有,欢迎分享本文,转载请保留出处!

文件下载

老薛主机终身7折优惠码boke112

上一篇:
下一篇:

评论已关闭!