Created
June 18, 2018 11:04
-
-
Save azettl/0126b9d0c054c93a78e53730a7d92526 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
String.prototype.getParams = function (search) { | |
var params = null; | |
var paramsObject = new Object(); | |
if(search && search != ""){ | |
params = this.substr(this.indexOf(search) + search.length + 1, this.length); | |
return params.substr(0, ((params.indexOf("&") == "-1") ? params.length : params.indexOf("&"))); | |
} | |
params = this.substr(this.indexOf("?") + 1, this.length).split("&"); | |
for(i=0; i < params.length; i++){ | |
param = params[i].split("="); | |
paramsObject[param[0]] = param[1]; | |
} | |
return paramsObject; | |
}; | |
String.prototype.setParams = function (params) { | |
if(typeof(params) == "object"){ | |
var newurl = this; | |
for(var key in params){ | |
if(newurl.indexOf("&" + key) != "-1"){ | |
newurl = newurl.replace("&" + key + "=" + newurl.getParams(key), "&" + key + "=" + params[key]); | |
}else if(newurl.indexOf("?" + key) != "-1"){ | |
newurl = newurl.replace("?" + key + "=" + newurl.getParams(key), "?" + key + "=" + params[key]); | |
}else if(newurl.indexOf("?") != "-1"){ | |
newurl += "&" + key + "=" + params[key]; | |
}else{ | |
newurl += "?" + key + "=" + params[key]; | |
} | |
} | |
return newurl; | |
} | |
}; | |
var url = "http://www.google.de?hl=en&test=1&why=because"; | |
var params = new Object(); | |
params["hl"] = "de"; | |
params["test"] = 2; | |
params["newparam"] = "a"; | |
var newurl = url.setParams(params); | |
console.log(newurl); // http://www.google.de?hl=de&test=2&why=because&newparam=a |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment