The code is very simple. The main idea is to parse the url parameters into js objects, and then it is very convenient to add, delete, modify, and check. Take notes here.
Copy the code code as follows:
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 following parts
this.init();
}
//Analyze the url and get? The front is stored in this.href, the parameters are parsed into this.params objects, and the # and the following are stored in this.jing
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 url after the operation is composed of three parts
objURL.prototype.url=function(){
var strurl=this.href;
var objps=[];//Use array organization here, and then perform join operation
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 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, nothing else. Call:
Copy the code code as follows:
var myurl=new LG.URL("http://www.baidu.com?a=1");
myurl.set("b","hello"); //added b=hello
alert (myurl.url());
myurl.remove("b"); //Deleted b
alert(myurl.get ("a"));//Get the value of parameter a, here we get 1
myurl.set("a",23); //Modify the value of a to 23
alert (myurl.url());