JavaScript function to update/replace the value in a URL query string parameter; or insert the key/value if it doesn't exist.
/**
* Update URL Query String
*
* Updates the URL query string with the specified parameter value.
* If the key doesn't exist in the url, a new one will be created.
*
* @param {String} key The query string key to search for in the specified url parameter.
* @param {String|Number} value The value to replace in the existing query string.
* @param {String} url A url containing the query string key to update, or
* insert if one doesn't currently exist. If the url parameter is not
* provided, the browser url (window.location.href) will be used.
*
* @return {String} The updated url and query string.
*/
function updateUrlQueryString(key, value, url) {
value = encodeURIComponent(value);
var _url = url || window.location.href;
var re = new RegExp("([?&])" + key + "=.*?(&|#|$)(.*)", "gi"),
hash;
if (re.test(_url)) {
if (typeof value !== "undefined" && value !== null)
return _url.replace(re, "$1" + key + "=" + value + "$2$3");
else {
hash = _url.split("#");
_url = hash[0].replace(re, "$1$3").replace(/(&|\?)$/, "");
if (typeof hash[1] !== "undefined" && hash[1] !== null) {
_url += "#" + hash[1];
}
return _url;
}
} else {
if (typeof value !== "undefined" && value !== null) {
var separator = _url.indexOf("?") !== -1 ? "&" : "?";
hash = _url.split("#");
_url = hash[0] + separator + key + "=" + value;
if (typeof hash[1] !== "undefined" && hash[1] !== null) {
_url += "#" + hash[1];
}
return _url;
} else return _url;
}
}
/**
* Gets URL Query String Parameter Value by Name
*
* Gets the value for the specified URL query string parameter name.
*
* @param {String} parameterName The name of the url query string parameter to search for.
* @param {String} url The url to search. If the url parameter is not provided,
* the browser url (window.location.href) will be used.
*
* @return {String} The value found in the specified url for the matched
* parameterName, or null if not found.
*/
function getUrlQueryStringParameter(parameterName, url) {
var _url = url || window.location.href;
parameterName = parameterName.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + parameterName + "(=([^&#]*)|&|#|$)", "i"),
results = regex.exec(_url);
if (!results) return null;
if (!results[2]) return "";
return decodeURIComponent(results[2].replace(/\+/g, " "));
}