Skip to content

Instantly share code, notes, and snippets.

@Znarkus
Last active December 22, 2015 08:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Znarkus/6444017 to your computer and use it in GitHub Desktop.
Save Znarkus/6444017 to your computer and use it in GitHub Desktop.
Change a query parameter in the current URL.
function changeUrlParam(paramName, newValue) {
var search = location.search.replace(new RegExp('[?&]' + paramName + '=[^&]+'), ''),
url = location.pathname + search;
if (newValue !== null) {
url += (search ? '&' : '?') +
paramName + '=' + newValue;
}
location = url;
}

For URL /foo/bar?param=5 the code changeUrlParam('param', 6) will redirect to /foo/bar?param=6
For URL /foo/bar?param=5 the code changeUrlParam('param', null) will redirect to /foo/bar

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment