Skip to content

Instantly share code, notes, and snippets.

@munir131
Created May 13, 2016 12:04
Show Gist options
  • Save munir131/520d2b43272db54f238ae54e787cbde2 to your computer and use it in GitHub Desktop.
Save munir131/520d2b43272db54f238ae54e787cbde2 to your computer and use it in GitHub Desktop.
Functions for read write remove value from URL
window.getValueFromURL = function (name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
};
window.setToURL = function (key, value) {
var queryString;
window.removeFromURL(key);
if (value) {
if (document.URL.indexOf('?') === -1) {
queryString = '?' + $.param(JSON.parse('{"' + key + '" : "' + value + '"}'));
} else {
queryString = '&' + $.param(JSON.parse('{"' + key + '" : "' + value + '"}'));
}
history.pushState({},'',location.toString() + queryString);
}
};
window.removeFromURL = function (key) {
var sourceURL = location.toString();
var rtn = sourceURL.split("?")[0],
param,
params_arr = [],
queryString = (sourceURL.indexOf("?") !== -1) ? sourceURL.split("?")[1] : "";
if (queryString !== "") {
params_arr = queryString.split("&");
for (var i = params_arr.length - 1; i >= 0; i -= 1) {
param = params_arr[i].split("=")[0];
if (param === key) {
params_arr.splice(i, 1);
}
}
var finalQueryString = params_arr.join("&");
if (finalQueryString.length > 0) {
rtn = rtn + "?" + finalQueryString;
}
}
history.pushState({},'',rtn);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment