Skip to content

Instantly share code, notes, and snippets.

@chieft3ch
Created February 4, 2019 15:39
Show Gist options
  • Save chieft3ch/df3cc28e8e9bfbbe539b0a464d440efc to your computer and use it in GitHub Desktop.
Save chieft3ch/df3cc28e8e9bfbbe539b0a464d440efc to your computer and use it in GitHub Desktop.
Add, Remove and Get URL Parameters in Javascript
// Insert URL parameter
function insertUrlParameter(key, value)
{
key = encodeURI(key); value = encodeURI(value);
var kvp = document.location.search.substr(1).split('&');
var i=kvp.length; var x; while(i--)
{
x = kvp[i].split('=');
if (x[0]==key)
{
x[1] = value;
kvp[i] = x.join('=');
break;
}
}
if(i<0) {kvp[kvp.length] = [key,value].join('=');}
document.location.search = kvp.join('&');
}
// Get URL Parameter
function getUrlParameter(Param)
{
var PageURL = window.location.search.substring(1),
URLVariables = PageURL.split('&'),
ParameterName,
i;
for (i = 0; i < URLVariables.length; i++) {
ParameterName = URLVariables[i].split('=');
if (ParameterName[0] === Param) {
return ParameterName[1] === undefined ? true : decodeURIComponent(ParameterName[1]);
}
}
}
// Remove URL parameter
function removeUrlParameter(Param)
{
var url = window.location.href.split('?')[0]+'?';
var PageURL = decodeURIComponent(window.location.search.substring(1)),
URLVariables = PageURL.split('&'),
ParameterName,
i;
for (i = 0; i < URLVariables.length; i++) {
ParameterName = URLVariables[i].split('=');
if (ParameterName[0] != Param) {
url = url + ParameterName[0] + '=' + ParameterName[1] + '&'
}
}
window.location = url.substring(0,url.length-1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment