183

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?

1

11 Answers 11

209

Solution:

let url = window.location.href;    
if (url.indexOf('?') > -1){
   url += '&param=1'
} else {
   url += '?param=1'
}
window.location.href = url;
11
  • 1
    str.search( regex ) is faster than srt.indexOf( str2 )
    – xavierm02
    May 13, 2011 at 20:41
  • 1
    And you should give a ull example with a variable name and a variable parameter with encodeURIComponent().
    – xavierm02
    May 13, 2011 at 20:41
  • And insteand of > -1, you should use !== -1
    – xavierm02
    May 13, 2011 at 20:42
  • 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, 2011 at 0: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: stackoverflow.com/questions/486896/… Aug 21, 2011 at 18:44
181

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.

8
  • 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'; Sep 2, 2015 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. Jan 10, 2017 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. Jan 11, 2017 at 14:03
  • 1
    My bad @BoFrederiksen you are indeed correct...srry about that. "+=" of coarse...missed that. +1 from me. Jan 11, 2017 at 15:27
  • Will this work in a tag? Etc.: <a href="javascript:window.location.search += '&param=42';">
    – zygimantus
    Mar 20, 2017 at 9:12
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');
3
  • 1
    Why not just to use : if(window.location.search.indexOf('&param=') == -1) {window.location.search += '&param=1';}
    – TOPKAT
    Mar 29, 2016 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, 2016 at 0:50
  • 1
    this is the best answer, works without modification Dec 10, 2020 at 19:03
28

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;
2
  • 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. Jun 21, 2021 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. Feb 17, 2022 at 15:24
7
location.href = location.href + "&parameter=" + value;
2
  • 6
    Parameters getting duplicated May 30, 2018 at 12:50
  • I used this for Cypress and it worked perfectly! Thanks! Nov 18, 2022 at 23:48
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).

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;
}
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;
0
1

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

Change:

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

To:

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

1
  • Please post such corrections in a comment or propose and edit. They don't warrant a separate answer.
    – JJJ
    Apr 4, 2019 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

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.