Parse query string in JavaScript

Possible Duplicate:
How can I get query string values?

I need to parse the query string www.mysite.com/default.aspx?dest=aboutus.aspx . How do I get the dest variable in JavaScript?


Here is a fast and easy way of parsing query strings in 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);
}

Now make a request to 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;
}

Turns query string like hello=1&another=2 into object {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" . 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.


You can also use the excellent URI.js library by Rodney Rehm. Here's how:-

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

And to parse the query string of current page:-

var $_GET = URI(document.URL).query(true); // ala PHP
    alert($_GET['dest']); // == aboutus.aspx 
链接地址: http://www.djcxy.com/p/17594.html

上一篇: jquery从URL获取查询字符串

下一篇: 在JavaScript中解析查询字符串