Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a parameter to the URL?

My current URL is: http://something.com/mobiles.php?brand=samsung

Now when a user clicks on a minimum price filter (say 300), I want my URL to become

http://something.com/mobiles.php?brand=samsung&priceMin=300

In other words, I am looking for a javascript function which will add a specified parameter in the current URL and then re-direct the webpage to the new URL.

Note: If no parameters are set then the function should add ? instead of &

i.e. if the current URL is http://something.com/mobiles.php then page should be re-directed to http://something.com/mobiles.php?priceMin=300 instead of http://something.com/mobiles.php&priceMin=300

like image 441
sumit Avatar asked Aug 01 '11 13:08

sumit


People also ask

Where is the parameter in URL?

What Are URL Parameters? Also known by the aliases of query strings or URL variables, parameters are the portion of a URL that follows a question mark. They are comprised of a key and a value pair, separated by an equal sign. Multiple parameters can be added to a single page by using an ampersand.

How do I pass a parameter to a link in HTML?

In order to send the parameters in the URL you donot need to enclose the value inside quote ('') or doublequotes ("") . You just need to send the values (or the multiple values) as shown below.. Also keep in mind that you need to keep track of the urlencoding.


2 Answers

try something like this, it should consider also cases when you already have that param in url:

function addOrUpdateUrlParam(name, value)
{
  var href = window.location.href;
  var regex = new RegExp("[&\\?]" + name + "=");
  if(regex.test(href))
  {
    regex = new RegExp("([&\\?])" + name + "=\\d+");
    window.location.href = href.replace(regex, "$1" + name + "=" + value);
  }
  else
  {
    if(href.indexOf("?") > -1)
      window.location.href = href + "&" + name + "=" + value;
    else
      window.location.href = href + "?" + name + "=" + value;
  }
}

then you invoke it like in your case:

addOrUpdateUrlParam('priceMin', 300);
like image 149
petho Avatar answered Sep 19 '22 14:09

petho


Actually this is totally trivial, because the javascript location object already deals with this. Just encapsulate this one-liner into a function to re-use it with links etc:

<script>
    function addParam(v) {
        window.location.search += '&' + v;
    }
</script>

<a href="javascript:addParam('priceMin=300');">add priceMin=300</a>

There is no need to check for ? as this is already the search part and you only need to add the param.

If you don't want to even make use of a function you can write as so:

<a href="javascript:location.search+='&priceMin=300';">add priceMin=300</a>

Keep in mind that this does exactly what you've asked for: To add that specific parameter. It can already be part of the search part because you can have the same parameter more than once in an URI. You might want to normalize that within your application, but that's another field. I would centralize URL-normalization into a function of it's own.

Edit:

In discussion about the accepted answer above it became clear, that the following conditions should be met to get a working function:

  • if the parameter already exists, it should be changed.
  • if the parameter already exists multiple times, only the changed copy should survive.
  • if the parameter already exists, but have no value, the value should be set.

As search already provides the search string, the only thing left to achieve is to parse that query-info part into the name and value pairs, change or add the missing name and value and then add it back to search:

<script>
    function setParam(name, value) {
        var l = window.location;

        /* build params */
        var params = {};        
        var x = /(?:\??)([^=&?]+)=?([^&?]*)/g;        
        var s = l.search;
        for(var r = x.exec(s); r; r = x.exec(s))
        {
            r[1] = decodeURIComponent(r[1]);
            if (!r[2]) r[2] = '%%';
            params[r[1]] = r[2];
        }

        /* set param */
        params[name] = encodeURIComponent(value);

        /* build search */
        var search = [];
        for(var i in params)
        {
            var p = encodeURIComponent(i);
            var v = params[i];
            if (v != '%%') p += '=' + v;
            search.push(p);
        }
        search = search.join('&');

        /* execute search */
        l.search = search;
    }
</script>

<a href="javascript:setParam('priceMin', 300);">add priceMin=300</a>

This at least is a bit more robust as it can deal with URLs like these:

test.html?a?b&c&test=foo&priceMin=300

Or even:

test.html?a?b&c&test=foo&pri%63eMin=300

Additionally, the added name and value are always properly encoded. Where this might fail is if a parameter name results in an illegal property js label.

like image 27
hakre Avatar answered Sep 22 '22 14:09

hakre