Well, I've been searching some functions for handle URL parameters to replace or remove on both of javascript or jQuery. However, I didn't find any fit one. This is what I wrote for such usage:
//Handle URL parameter, if newvalue is empty, remove the parameter or replace with new value.
replaceUrlParameter = function (url, param, newvalue) {
if (url.indexOf("#")) {
url = url.split("#")[0];
}
var headUrl = url.split("?")[0];
var arrayParam = url.split("?")[1].split("&");
var idx = null;
for (i = 0; i < arrayParam.length; i++) {
if (arrayParam[i].split("=")[0] == param) {
idx = i;
}
}
if (idx != null) {
var newUrl = null;
if (newvalue != "") {
var newParam = param + "=" + newvalue;
newUrl = arrayParam.splice(idx, 1, newParam);
}
else {
var removedArray = arrayParam.splice(idx, 1);
newUrl = headUrl + "?" + arrayParam.join("&");
}
return newUrl;
}
else
{ return url; }
return url;
}
No comments:
Post a Comment