Javascript Remove a parameter from the query sring if found in current url - Code-Tips.com - Web Development, Programming, SEO

Sunday, February 13, 2011

Javascript Remove a parameter from the query sring if found in current url

This Javascript function removes the supplied parameter from the query string if it is present in the current url.  This is done by converting the query string into an array of parameters and values, then rebuilding the final string to exclude the parameter supplied to the function.  The browser is then redirected to the current page with the new query string.


function removeParameter(parameter)
{
   //Get Query String from url
   fullQString = window.location.search.substring(1);
   
   paramCount = 0;
   queryStringComplete = "?";

   if(fullQString.length > 0)
   {
       //Split Query String into separate parameters
       paramArray = fullQString.split("&");
       
       //Loop through params, check if parameter exists.  
       for (i=0;i<paramArray.length;i++)
       {
         currentParameter = paramArray[i].split("=");
         if(currentParameter[0] == parameter) //Parameter already exists in current url
         {
            //don't include existing (will be appended to end of url)
         }
         else //Existing unrelated parameter
         {
            if(paramCount > 0)
               queryStringComplete = queryStringComplete + "&";
           
            queryStringComplete = queryStringComplete + paramArray[i];
            paramCount++;
         }
       }
   }
   
   window.location = self.location.protocol + '//' + self.location.host + self.location.pathname + queryStringComplete;
}


Next: Javascript Get the value of the specified Query String Parameter

Previous: Javascript Check if Query String Parameter Exists in current URL

Javascript Query String Manipulation (TOC)

0 comments:

Post a Comment

Understood
This website is using cookies. More details