解析QueryString的JavaScript类

分享JavaScript by 达达 at 2010-01-17

以前写的一个解析QueryString的JS类,可以获取或设置QueryString中的值,记下了方便找 :)

使用示例:

var qs = new QueryString(query);

qs.set("ajaxids", ids)
qs.set("ajaxsn", new Date())

query = qs.toStr();

也可以连续调用:

query = new QueryString(query).set("ajaxids", ids).set("ajaxsn", new Date()).toStr();

其它用法就自己看代码琢磨吧。

完整代码(2010年1月30日,更新 -- 精简代码):

QueryString = function(qs){
    this.p={};

    if(!qs) qs=location.search;

    if(qs){
        var reg = /(?:^?|&)(.*?)=(.*?)(?=&|$)/g, temp;
        while((temp = reg.exec(params)) != null) this.p[decodeURIComponent(temp[1])] = decodeURIComponent(temp[2]);
    }

    this.set = function(name, value){
        this.p[name] = value;
        return this;
    };

    this.get = function(name, def){
        var v = this.p[name];
        return (v != null) ? v : def;
    };

    this.has = function(name){
        return this.p[name] != null;
    };

    this.toStr = function(){
        var r = '?';
        for (var k in this.p) r += encodeURIComponent(k) + '=' + encodeURIComponent(this.p[k]) + '&';
        return r;
    };
};

注:其中的QueryString解析过程,来源于sohighthesky的《javascript获取url参数和script标签中获取url参数》,多谢sohighthesky的分享!

完整代码(原始版本):

QueryString = function(qs){
    this.p={};

    if(!qs)
        qs=location.search;

    if(qs) {
        var b = qs.indexOf('?');
        var e = qs.indexOf('#');

        if(b >= 0){
            qs = e < 0 ? qs.substr(b + 1) : qs.substring(b + 1,e);

            if(qs.length > 0){
                qs = qs.replace(/+/g, ' ');

                var a = qs.split('&');

                for (var i = 0; i < a.length; i++) {
                    var t = a[i].split('=');
                    var n = decodeURIComponent(t[0]);
                    var v = (t.length == 2) ? decodeURIComponent(t[1]) : n;
                    this.p[n] = v;
                }
            }
        }
    }

    this.set = function(name, value){
        this.p[name] = value;
        return this;
    };

    this.get = function(name, def){
        var v = this.p[name];
        return (v != null) ? v : def;
    };

    this.has = function(name) {
        return this.p[name] != null;
    };

    this.toStr = function() {
        var r='?';
        for (var k in this.p) {
            r += encodeURIComponent(k) + '=' + encodeURIComponent(this.p[k]) + '&';
        }
        return r;
    };
};