3

I am working on a web application where I need to add and remove variables from the URL. I have done on click adding variables to the URL but I it adds duplicates variable.

href="http://localhost<?php echo $_SERVER['REQUEST_URI'];?>?budget=1-lakh-3-lakh"

First Click on link:

http://localhost/auto/search.php?budget=1-2L

Second Click on same link:

http://localhost/auto/search.php?budget=1-2L&budget=1-2L

I want to remove variable from the URL if it is already exist else add variable on a link click. I already tried lot's of method but I am not getting the result. With jQuery I tried replace(), indexOf().

2
  • Are you submitting a form or using a link <a>? If the href of a "a" tag is define as above, the variables will not be added after the existing one. Commented Jan 24, 2013 at 18:22
  • I am using link, In general on same link click I want to add or remove some parameters from the link. On each click page will get refreshed. Commented Jan 24, 2013 at 18:28

1 Answer 1

3

Here is a code to remove a specific parameter from an URL :

var url = location.href.replace(/&?budget=([^&]$|[^&]*)/i, "");  

or the function :

function removeParameterFromUrl(url,parameterName)
{
    var reg = new RegExp('&?'+parameterName+'=([^&]$|[^&]*)','gi');     
    return url.replace(reg, ""); 
}

location.href = removeParameterFromUrl(location.href,'budget')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.