Skip to content

Instantly share code, notes, and snippets.

@pierre-b
Last active June 13, 2016 14:35
Show Gist options
  • Save pierre-b/406ed9b9d7396499aa80 to your computer and use it in GitHub Desktop.
Save pierre-b/406ed9b9d7396499aa80 to your computer and use it in GitHub Desktop.
Update or remove a parameter in a URL
// update a parameter in a URL
// or removes it if value is null
// browser should support forEach() function or use a polyfill
var updateUrlParameter = function(url, key, value){
var parser = document.createElement('a');
parser.href = url;
var newUrl = parser.protocol+'//'+parser.host+parser.pathname;
// has parameters ?
if(parser.search && parser.search.indexOf('?') !== -1){
// parameter already exists
if(parser.search.indexOf(key+'=') !== -1) {
// paramters to array
var params = parser.search.replace('?', '');
params = params.split('&');
params.forEach(function(param, i){
if(param.indexOf(key+'=') !== -1) {
if(value !== null) params[i] = key+'='+value;
else delete params[i];
}
});
if(params.length > 0) newUrl += '?'+params.join('&');
}
else if(value !== null) newUrl += parser.search+'&'+key+'='+value; // append new parameter
else newUrl += parser.search; // skip the value (remove)
}
else if(value !== null) newUrl += '?'+key+'='+value; // no parameters, create it
newUrl += parser.hash;
return newUrl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment