Skip to content

Instantly share code, notes, and snippets.

@vermilion1
Created August 21, 2014 17:38
Show Gist options
  • Save vermilion1/af0a9acbcd24edcdc82c to your computer and use it in GitHub Desktop.
Save vermilion1/af0a9acbcd24edcdc82c to your computer and use it in GitHub Desktop.
Update search parameter
/**
* Update the param value of the passed URI.
* In case parameter wasn't found we have to add it.
* @param {string} uri - URI.
* @param {string} key - Parameter name.
* @param {string} value - Parameter value.
* @returns {string} Updated URI.
*/
var updateQueryStringParameter = function (uri, key, value) {
var re = new RegExp('([?&])' + key + '=.*?(&|$)', 'i');
var hasSearch = uri.indexOf('?') !== -1;
var separator = hasSearch ? '&' : '?';
if (uri.match(re)) {
return uri.replace(re, '$1' + key + '=' + value + '$2');
} else {
var split = uri.split('#');
var hash = split[1];
return split[0] + separator + key + '=' + value + (hash ? '#' + hash : '');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment