Js gets the url parameter code instance to share the url of the of js operation

  • 2020-03-30 00:52:32
  • OfStack

The code is very simple, the main idea is to resolve the url parameters to js object, and then do add, delete, change, look up operations is very convenient ~, here to take notes.


var LG=(function(lg){
    var objURL=function(url){
        this.ourl=url||window.location.href;
        this.href="";//? The front part
        this.params={};//Url parameter object
        this.jing="";//# and the rest
        this.init();
    }
    //Analyze the url and get? Save this.href in front, resolve the parameter as this.params object, and save this.jing after the # sign
    objURL.prototype.init=function(){
        var str=this.ourl;
        var index=str.indexOf("#");
        if(index>0){
            this.jing=str.substr(index);
            str=str.substring(0,index);
        }
        index=str.indexOf("?");
        if(index>0){
            this.href=str.substring(0,index);
            str=str.substr(index+1);
            var parts=str.split("&");
            for(var i=0;i<parts.length;i++){
                var kv=parts[0].split("=");
                this.params[kv[0]]=kv[1];
            }
        }
        else{
            this.href=this.ourl;
            this.params={};
        }
    }
    //Just modify this.params
    objURL.prototype.set=function(key,val){
        this.params[key]=val;
    }
    //Just set this.params
    objURL.prototype.remove=function(key){
        this.params[key]=undefined;
    }
    //The resulting url is composed of three parts
    objURL.prototype.url=function(){
        var strurl=this.href;
        var objps=[];//I'm going to use an array here, and then I'm going to do join
        for(var k in this.params){
            if(this.params[k]){
                objps.push(k+"="+this.params[k]);
            }
        }
        if(objps.length>0){
            strurl+="?"+objps.join("&");
        }
        if(this.jing.length>0){
            strurl+=this.jing;
        }
        return strurl;
    }
    //Get the parameter value
    objURL.prototype.get=function(key){
        return this.params[key];
    }    
    lg.URL=objURL;
    return lg;
}(LG||{}));

LG is just my personal common JS namespace, without him. Call:


var myurl=new LG.URL("http://www.baidu.com?a=1");

    myurl.set("b","hello"); //Add the b = hello
    alert (myurl.url());

    myurl.remove("b"); //Remove the b

    alert(myurl.get ("a"));//Take the value of parameter a, and you get 1 here

    myurl.set("a",23); //Modify the value of a to be 23

    alert (myurl.url());


Related articles: