Skip to content

Instantly share code, notes, and snippets.

@anton-rudeshko
Created April 1, 2014 12:07
Show Gist options
  • Save anton-rudeshko/9912630 to your computer and use it in GitHub Desktop.
Save anton-rudeshko/9912630 to your computer and use it in GitHub Desktop.
function replaceUrl(key, newValue) {
var url = window.location.href,
separator = ~url.indexOf('?') ? '&' : '?',
re = new RegExp('([?&])' + key + '=(.*?)([?&]|$)', 'i'),
match = re.exec(url),
hasParam = !!match;
if (hasParam) {
if (match[2] === newValue || !newValue) {
return url.replace(re, '');
}
return url.replace(re, '$1' + key + '=' + newValue + '$3');
}
return url + separator + key + '=' + (newValue || '1');
}
function toggle(key, newValue) {
window.location.href = replaceUrl(key, newValue);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment