181

I am looking to write a piece of javascript that will append a parameter to the current URL and then refresh the page - how can I do this?

Syscall
  • 19,327
  • 10
  • 37
  • 52
amateur
  • 43,371
  • 65
  • 192
  • 320

11 Answers11

208

Solution:

let url = window.location.href;    
if (url.indexOf('?') > -1){
   url += '&param=1'
} else {
   url += '?param=1'
}
window.location.href = url;
Blackbam
  • 17,496
  • 26
  • 97
  • 150
Shlomi Komemi
  • 5,445
  • 3
  • 28
  • 41
  • 1
    str.search( regex ) is faster than srt.indexOf( str2 ) – xavierm02 May 13 '11 at 20:41
  • 1
    And you should give a ull example with a variable name and a variable parameter with encodeURIComponent(). – xavierm02 May 13 '11 at 20:41
  • And insteand of > -1, you should use !== -1 – xavierm02 May 13 '11 at 20:42
  • And the only difference here bewteew the if and the else if ? or &. Therefore the rest should be added ouside of it (here, "param=1" is duplicated). – xavierm02 May 13 '11 at 20:43
  • 14
    one follow up to this, how can add some logic that if the parameter already exists in a url i update its value rather than add a new parameter? – amateur May 14 '11 at 00:36
  • 1
    this will take the anchor (hash value) off the url, if it existed, @amateur you can find a function that does that here: http://stackoverflow.com/questions/486896/adding-a-parameter-to-the-url-with-javascript – Doug Molineux Aug 21 '11 at 18:44
  • I like the easy way, compare to all (+/- long) functions I found before ! – Sebastien Dec 01 '15 at 16:07
  • This answer will update the parameter, create if it doesn't exist etc: https://stackoverflow.com/questions/5999118/how-can-i-add-or-update-a-query-string-parameter – Josh Harris Feb 02 '21 at 15:15
  • 7 lines of code! I did the same in [one line](https://stackoverflow.com/questions/5997450/append-to-url-and-refresh-page/5998205#5998205). – Bo Frederiksen Mar 03 '21 at 19:03
  • What an odd (and also untrue) comment. Either could be useful in certain (different) cases, but the functionality is *not* the same. – ashleedawg Jun 19 '21 at 16:08
179

Shorter than the accepted answer, doing the same, but keeping it simple:

window.location.search += '&param=42';

We don't have to alter the entire url, just the query string, known as the search attribute of location.

When you are assigning a value to the search attribute, the question mark is automatically inserted by the browser and the page is reloaded.

Bo Frederiksen
  • 2,087
  • 1
  • 14
  • 21
  • 18
    For a case where you know this will be the only parameter, you can also set search instead of appending to it: `window.location.search = '?param=42';` – Dave DuPlantis Sep 02 '15 at 17:12
  • What if your url is: www.mysite.com ...then won't it make the url: www.mysite.com&param=42 which would need the "?" character since its the only parameter in the url. I like @Shlomi Komemi answer as it covers those 2 main scenarios. – greaterKing Jan 10 '17 at 18:57
  • 1
    @greaterKing the browser adds the question mark, when adding parameters to the search attribute of location. Try it in your browsers console. – Bo Frederiksen Jan 11 '17 at 14:03
  • 1
    My bad @BoFrederiksen you are indeed correct...srry about that. "+=" of coarse...missed that. +1 from me. – greaterKing Jan 11 '17 at 15:27
  • Will this work in `a` tag? Etc.: `` – zygimantus Mar 20 '17 at 09:12
  • This everytime appends. What if `param` is already there and just want to change the value of it? – Anuj TBE Sep 12 '18 at 18:21
  • @AnujTBE Changing an existing value is a more complicated use case that the original question describes. – Bo Frederiksen Sep 18 '18 at 14:05
  • Best , can you help me with this, everytime i click it adds the same parameter to the URL i want to toggle it like, if the value of parameter is 1 then add 0 . – Amani Oct 03 '18 at 17:59
90

Most of the answers here suggest that one should append the parameter(s) to the URL, something like the following snippet or a similar variation:

location.href = location.href + "&parameter=" + value;

This will work quite well for the majority of the cases.

However

That's not the correct way to append a parameter to a URL in my opinion.

Because the suggested approach does not test if the parameter is already set in the URL, if not careful one may end up with a very long URL with the same parameter repeated multiple times. ie:

https://stackoverflow.com/?&param=1&param=1&param=1&param=1&param=1&param=1&param=1&param=1&param=1

at this point is where problems begin. The suggested approach could and will create a very long URL after multiple page refreshes, thus making the URL invalid. Follow this link for more information about long URL What is the maximum length of a URL in different browsers?

This is my suggested approach:

function URL_add_parameter(url, param, value){
    var hash       = {};
    var parser     = document.createElement('a');

    parser.href    = url;

    var parameters = parser.search.split(/\?|&/);

    for(var i=0; i < parameters.length; i++) {
        if(!parameters[i])
            continue;

        var ary      = parameters[i].split('=');
        hash[ary[0]] = ary[1];
    }

    hash[param] = value;

    var list = [];  
    Object.keys(hash).forEach(function (key) {
        list.push(key + '=' + hash[key]);
    });

    parser.search = '?' + list.join('&');
    return parser.href;
}

With this function one just will have to do the following:

location.href = URL_add_parameter(location.href, 'param', 'value');
Community
  • 1
  • 1
yeyo
  • 2,954
  • 2
  • 29
  • 40
  • 1
    Why not just to use : `if(window.location.search.indexOf('&param=') == -1) {window.location.search += '&param=1';}` – TOPKAT Mar 29 '16 at 21:52
  • 2
    @SébastienGarcia-Roméo Yes that's an interesting approach, and indeed valid, however, there are two reasons as of why the function is programmed in that way. 1. To eliminate existing duplicate parameters. 2. To overwrite the value of an existing parameter. From this point of view, now the use of `indexOf` might introduce unnecessary complexity to the code. – yeyo Mar 30 '16 at 00:50
  • 1
    this is the best answer, works without modification – Lenka Pitonakova Dec 10 '20 at 19:03
27

If you are developing for a modern browser, Instead of parsing the url parameters yourself- you can use the built in URL functions to do it for you like this:

const parser = new URL(url || window.location);
parser.searchParams.set(key, value);
window.location = parser.href;
Kade
  • 901
  • 13
  • 18
  • 1
    I think this is the cleanest method since if you already have params in the url, with the other ones you would be repeating them. – Luciano Fantuzzi Jun 21 '21 at 14:52
  • 1
    Very nice solution, but the URL API is not supported by Internet Explorer. The good news is, that Internet Explorer 11 will be retired and go out of Microsoft support on June 15, 2022. – Bo Frederiksen Feb 17 '22 at 15:24
7
location.href = location.href + "&parameter=" + value;
Paul Alexander
  • 31,970
  • 14
  • 96
  • 151
3

This line of JS code takes the link without params (ie before '?') and then append params to it.

window.location.href = (window.location.href.split('?')[0]) + "?p1=ABC&p2=XYZ";

The above line of code is appending two params p1 and p2 with respective values 'ABC' and 'XYZ' (for better understanding).

William Prigol Lopes
  • 1,803
  • 14
  • 31
Anmol
  • 490
  • 6
  • 8
2
function gotoItem( item ){
    var url = window.location.href;
    var separator = (url.indexOf('?') > -1) ? "&" : "?";
    var qs = "item=" + encodeURIComponent(item);
    window.location.href = url + separator + qs;
}

More compat version

function gotoItem( item ){
    var url = window.location.href;    
    url += (url.indexOf('?') > -1)?"&":"?" + "item=" + encodeURIComponent(item);
    window.location.href = url;
}
epascarello
  • 204,599
  • 20
  • 195
  • 236
1

Please check the below code :

/*Get current URL*/    
var _url = location.href; 
/*Check if the url already contains ?, if yes append the parameter, else add the parameter*/
_url = ( _url.indexOf('?') !== -1 ) ? _url+'&param='+value : _url+'?param='+value;
/*reload the page */
window.location.href = _url;
Mohit Kanwar
  • 2,962
  • 7
  • 39
  • 59
Aftab
  • 330
  • 4
  • 16
1

One small bug fix for @yeyo's thoughtful answer above.

Change:

var parameters = parser.search.split(/\?|&/);

To:

var parameters = parser.search.split(/\?|&amp;/);

Gabrien
  • 53
  • 1
  • 8
  • Please post such corrections in a comment or propose and edit. They don't warrant a separate answer. – JJJ Apr 04 '19 at 19:02
1

Try this

var url = ApiUrl(`/customers`);
  if(data){
   url += '?search='+data; 
  }
  else
  { 
      url +=  `?page=${page}&per_page=${perpage}`;
  }
  console.log(url);
1

Also:

window.location.href += (window.location.href.indexOf('?') > -1 ? '&' : '?') + 'param=1'

Just one liner of Shlomi answer usable in bookmarklets

estani
  • 24,254
  • 2
  • 93
  • 76