Adding a parameter to the URL with JavaScript
Asked Answered
S

37

520

In a web application that makes use of AJAX calls, I need to submit a request but add a parameter to the end of the URL, for example:

Original URL:

http://server/myapp.php?id=10

Resulting URL:

http://server/myapp.php?id=10&enabled=true

Looking for a JavaScript function which parses the URL looking at each parameter, then adds the new parameter or updates the value if one already exists.

Swam answered 28/1, 2009 at 8:33 Comment(6)
Have you searched for javascript url parsers ? You could make your own, splitting on every &-character, but it's probably easier just to use existing code.Fuse
I had a similar scenario once and I found this article by Peter Bromberg very helpful :Bedmate
window.history.pushState('page2', 'Title', document.location+'/page2.php'); will do your work without loading pageNode
This question have better answers here #6954444Diarrhea
unbelievable this isnt native in this poor language that JS is....Morissa
This is very nice and lightweight library: medialize.github.io/URI.jsStatesman
T
238

A basic implementation which you'll need to adapt would look something like this:

function insertParam(key, value) {
    key = encodeURIComponent(key);
    value = encodeURIComponent(value);

    // kvp looks like ['key1=value1', 'key2=value2', ...]
    var kvp = document.location.search.substr(1).split('&');
    let i=0;

    for(; i<kvp.length; i++){
        if (kvp[i].startsWith(key + '=')) {
            let pair = kvp[i].split('=');
            pair[1] = value;
            kvp[i] = pair.join('=');
            break;
        }
    }

    if(i >= kvp.length){
        kvp[kvp.length] = [key,value].join('=');
    }

    // can return this or...
    let params = kvp.join('&');

    // reload page with new params
    document.location.search = params;
}

This is approximately twice as fast as a regex or search based solution, but that depends completely on the length of the querystring and the index of any match


the slow regex method I benchmarked against for completions sake (approx +150% slower)

function insertParam2(key,value)
{
    key = encodeURIComponent(key); value = encodeURIComponent(value);

    var s = document.location.search;
    var kvp = key+"="+value;

    var r = new RegExp("(&|\\?)"+key+"=[^\&]*");

    s = s.replace(r,"$1"+kvp);

    if(!RegExp.$1) {s += (s.length>0 ? '&' : '?') + kvp;};

    //again, do what you will here
    document.location.search = s;
}
Traduce answered 28/1, 2009 at 9:50 Comment(13)
thanks again. see lessanvaezi.com/wp-content/uploads/2009/01/test.html for a basic comparison of the methodsSwam
Nice function, annakata :) but in many cases, url parameters are case insensitive. Wouldn't it be wise to make the function case insensitive as well?Pestalozzi
Using escape() to escape URL parameters is wrong. It breaks for values with "+" in them. You should be using encodeURIComponent instead. Full discussion: xkr.us/articles/javascript/encode-compareAghast
I am calling this function and the page is reloading in infinite loop. Please help!Overcompensation
@iSumitG instead of location.search you can use location.hash so it won't reload ... just replace all the instances of location.search with location.hashFidellas
@Darwin I wouldn't say it is wrong, just different from what you might expect. One could just as easily say it is wrong to use values with + in them.Kaila
Top implementation doesn't handle empty location.search properly. See Mehdi's answer for updated solution.Kaila
when no parameters are already in the url you get a ?&param=valueJasik
and this function doesn't support multiple addition of querystring.Brickkiln
Shouldn't you be using encodeURIComponent rather than encodeURI? Otherwise any characters like =, & in your name or value will corrupt the URI.Nievesniflheim
I was inspired by the first solution - good idea, but not-readable code and it does not support more params at once, so I've made a new one that does accept an object with key: value, pairs and it is easily understand-able jsfiddle.net/1u9fqad3/1 UPDATE: fixed case when document.location.search is empty or 1 charPerseus
downvoted because it has bugs that were never fixed :)Experimentalize
Worked great! Also implemented a removeParam by replacing the for/if section with a .splice(idx, 1) and removing the if(i >= kvp.length){ blockDank
G
718

You can use one of these:

Example:

var url = new URL("http://foo.bar/?x=1&y=2");

// If your expected result is "http://foo.bar/?x=1&y=2&x=42"
url.searchParams.append('x', 42);

// If your expected result is "http://foo.bar/?x=42&y=2"
url.searchParams.set('x', 42);

You can use url.href or url.toString() to get the full URL

Glennaglennie answered 24/5, 2017 at 14:12 Comment(16)
I'd like to add a query parameter without a value, e.g. adding XML to http://foo.bar/?x=1&y=2 so that the end result is http://foo.bar/?x=1&y=2&XML. Is this possible? I tried url.searchParams.set('XML');, url.searchParams.set('XML', null);, and url.searchParams.set('XML', undefined); - but none worked in Chrome 63.Bass
Thanks! Too bad it is not supported by iOS, yet. developer.mozilla.org/en-US/docs/Web/API/URLSearchParamsSandfly
Too bad IE doesn't support it.Woodsman
iOS does now support URLSearchParams (since 9 days after @kanji's comment)Condom
Good news @MJeffryes! Still not supported by IE and Netscape.Glennaglennie
Yes it's bad supported by IE, but there is a polyfill that can handle that: github.com/lifaon74/url-polyfillChaiken
Are you sure you can modify the URLs searchParams like that? The doc says the property is readonly allowing get access.Marque
url.searchParams is a read-only reference to a URLSearchParams object. It means than you cannot do: url.searchParam = new URLSearchParam(); But you can modify in-place the content of the object using .set(). It's like: const a = {b: 0} You cannot modify the reference: a = {b: 1} but you can modify the content of the object in-place: a.b = 1 Try it in your JS console ;-)Glennaglennie
This is definitely the best answer in 2020 (2021) - if your target browser(s) don't support it, I suggest using a polyfill (e.g. from polyfill.io)Stocktaking
@Abdull, have you tried url.searchParams.set('XML', '')?Gasper
@AndreyMikhaylov-lolmaus, certainly, you haven't tried url.searchParams.set('XML', '') either, because it doesn't work.Bass
@Bass You're right, I hadn't tried it. But I've tried it just now and it does work. Why wouldn't it? const foo = new URLSearchParams(); foo.set('XML', ''); foo.toString() // => "XML="Gasper
@AndreyMikhaylov-lolmaus, read my initial question again. XML vs XML=.Bass
if you use searchParams.add('x', null) it will generate ?x=null which will most likely not be what you expectPortfire
IE choose Death over accepting this.Apsis
IE is dead on 2022-06-15Glennaglennie
K
260

You can use URLSearchParams

const urlParams = new URLSearchParams(window.location.search);

urlParams.set('order', 'date');

window.location.search = urlParams;

.set first agrument is the key, the second one is the value.

Note: this is not supported in any version of Internet Explorer (but is supported in Edge)

Kletter answered 8/7, 2019 at 10:34 Comment(13)
Love the simplicity of this and that it uses native browser methodsUnopened
This is the correct answer and should be top-voted. This new API is the definitive for URL processingExfoliate
The URLSearchParams in this answer is not supported by IE. docsNobelium
Is IE still relevant? As Edge is here now?Mitigate
IE is still relevant if you are targeting Government (June, 2021).Cherokee
you have my 150 upvotes. Also, have a cookie!Triboelectricity
Kinda clunky for a definitive API. Wish it was a one liner.Clere
Doesn't work on url has no query, like /abc/Arondell
@Arondell In what way does it not work?Snapback
In response to the comments about relevance to Internet Explorer, it was retired on 15 June 2022. RIP ⚰️Terrellterrena
This is correct, but need to add .toString() to the UrlParams in the last line.Seedling
Any way to do this without reloading the page?Jarman
@Seedling Actually, no you don't need to do thatKletter
T
238

A basic implementation which you'll need to adapt would look something like this:

function insertParam(key, value) {
    key = encodeURIComponent(key);
    value = encodeURIComponent(value);

    // kvp looks like ['key1=value1', 'key2=value2', ...]
    var kvp = document.location.search.substr(1).split('&');
    let i=0;

    for(; i<kvp.length; i++){
        if (kvp[i].startsWith(key + '=')) {
            let pair = kvp[i].split('=');
            pair[1] = value;
            kvp[i] = pair.join('=');
            break;
        }
    }

    if(i >= kvp.length){
        kvp[kvp.length] = [key,value].join('=');
    }

    // can return this or...
    let params = kvp.join('&');

    // reload page with new params
    document.location.search = params;
}

This is approximately twice as fast as a regex or search based solution, but that depends completely on the length of the querystring and the index of any match


the slow regex method I benchmarked against for completions sake (approx +150% slower)

function insertParam2(key,value)
{
    key = encodeURIComponent(key); value = encodeURIComponent(value);

    var s = document.location.search;
    var kvp = key+"="+value;

    var r = new RegExp("(&|\\?)"+key+"=[^\&]*");

    s = s.replace(r,"$1"+kvp);

    if(!RegExp.$1) {s += (s.length>0 ? '&' : '?') + kvp;};

    //again, do what you will here
    document.location.search = s;
}
Traduce answered 28/1, 2009 at 9:50 Comment(13)
thanks again. see lessanvaezi.com/wp-content/uploads/2009/01/test.html for a basic comparison of the methodsSwam
Nice function, annakata :) but in many cases, url parameters are case insensitive. Wouldn't it be wise to make the function case insensitive as well?Pestalozzi
Using escape() to escape URL parameters is wrong. It breaks for values with "+" in them. You should be using encodeURIComponent instead. Full discussion: xkr.us/articles/javascript/encode-compareAghast
I am calling this function and the page is reloading in infinite loop. Please help!Overcompensation
@iSumitG instead of location.search you can use location.hash so it won't reload ... just replace all the instances of location.search with location.hashFidellas
@Darwin I wouldn't say it is wrong, just different from what you might expect. One could just as easily say it is wrong to use values with + in them.Kaila
Top implementation doesn't handle empty location.search properly. See Mehdi's answer for updated solution.Kaila
when no parameters are already in the url you get a ?&param=valueJasik
and this function doesn't support multiple addition of querystring.Brickkiln
Shouldn't you be using encodeURIComponent rather than encodeURI? Otherwise any characters like =, & in your name or value will corrupt the URI.Nievesniflheim
I was inspired by the first solution - good idea, but not-readable code and it does not support more params at once, so I've made a new one that does accept an object with key: value, pairs and it is easily understand-able jsfiddle.net/1u9fqad3/1 UPDATE: fixed case when document.location.search is empty or 1 charPerseus
downvoted because it has bugs that were never fixed :)Experimentalize
Worked great! Also implemented a removeParam by replacing the for/if section with a .splice(idx, 1) and removing the if(i >= kvp.length){ blockDank
H
68

This is very simple solution. Its doesn't control parameter existence, and it doesn't change existing value. It adds your parameter to end, so you can get latest value in your back-end code.

function addParameterToURL(param){
    _url = location.href;
    _url += (_url.split('?')[1] ? '&':'?') + param;
    return _url;
}
Hothead answered 26/1, 2011 at 23:5 Comment(7)
you should also account for "#" in the url.. here's some code slop: url = (url.indexOf("?") != -1 ? url.split("?")[0]+"?"+part+"&"+url.split("?")[1] : (url.indexOf("#") != -1 ? url.split("#")[0]+"?"+part+"#"+ url.split("#")[1] : url+'?'+part));Bambi
@Bambi this thing looks evil as hell, but it's exactly what I wanted. Thanks.Pomeranian
why split the url to check for the existence of a single character? also don't forget to encode...something more like function appendQs(url, key, value) { return url + (url.indexOf('?') >= 0 ? "&" : '?') + encodeURIComponent(key) + "=" + encodeURIComponent(value); };Costrel
Fix it. This function does not check whether the parameter is already supplied. I tested this and got https://localhost/preview/inventory.html?sortci=priceASC&sortci=priceASC&sortci=stitle.Bawdy
@Jay, why does it need fixing? Check your assumptions. Duplicate query string parameters are legal, the same as duplicate form fields. This is how checkbox lists are implemented.in HTML and these will get passed via query string if the form method=get.Pargeting
@Pargeting got it :) Turns out I was a dumb kid in '16 :)Bawdy
My query is full of duplicate strings lol, only one primary key. There's so many duplicate strings I have to break up the posts occasionallyColiseum
S
67

Thank you all for your contribution. I used annakata code and modified to also include the case where there is no query string in the url at all. Hope this would help.

function insertParam(key, value) {
        key = escape(key); value = escape(value);

        var kvp = document.location.search.substr(1).split('&');
        if (kvp == '') {
            document.location.search = '?' + key + '=' + value;
        }
        else {

            var i = kvp.length; var x; while (i--) {
                x = kvp[i].split('=');

                if (x[0] == key) {
                    x[1] = value;
                    kvp[i] = x.join('=');
                    break;
                }
            }

            if (i < 0) { kvp[kvp.length] = [key, value].join('='); }

            //this will reload the page, it's likely better to store this until finished
            document.location.search = kvp.join('&');
        }
    }
Subreption answered 16/12, 2009 at 21:36 Comment(3)
It would be better to change from escape(key) and escape(value) to encodeURIComponent function.Burnaby
should this actually check if (kvp.length==1 && kvp[0]="") ?Peccable
@CharlesL. better is if (document.location.search)Rations
F
35

Here's a vastly simplified version, making tradeoffs for legibility and fewer lines of code instead of micro-optimized performance (and we're talking about a few miliseconds difference, realistically... due to the nature of this (operating on the current document's location), this will most likely be ran once on a page).

/**
* Add a URL parameter (or changing it if it already exists)
* @param {search} string  this is typically document.location.search
* @param {key}    string  the key to set
* @param {val}    string  value 
*/
var addUrlParam = function(search, key, val){
  var newParam = key + '=' + val,
      params = '?' + newParam;

  // If the "search" string exists, then build params from it
  if (search) {
    // Try to replace an existance instance
    params = search.replace(new RegExp('([?&])' + key + '[^&]*'), '$1' + newParam);

    // If nothing was replaced, then add the new param to the end
    if (params === search) {
      params += '&' + newParam;
    }
  }

  return params;
};

You would then use this like so:

document.location.pathname + addUrlParam(document.location.search, 'foo', 'bar');
Field answered 13/4, 2010 at 13:45 Comment(6)
+1 I like how you can specify something other than document.location.searchKaila
+1 Awesome, I agree that legibility is more important than micro-optimization in this case and I'm glad to see someone took that approach. @Kaila Maybe that was a bug in the JS engine when you wrote that comment, but I just tested '$1' in this context and it works fine.Gaston
Thanks a lot for the solution, though I also get stuck if I want to replace a value and there is already a parameter there. Instead a & it writes $1Shudder
Garrett: Could you fix your answer so it replaces existing parameters correctly? It's just a matter of replacing [\?&] with ([\?&]) in the RegExp (I'd just edit it myself but I'm not sure if the community policy allows fixing bugs in answers).Pragmatist
This is not working with url like "domain.tld" its add "&" instead of "?"Brom
This is not working with url like "domain.tld#anchor"; its add "&" after the anchorBrom
L
31

There is a built-in function inside URL class that you can use it for easy dealing with query string key/value params:

const url = new URL(window.location.href);
// url.searchParams has several function, we just use `set` function
// to set a value, if you just want to append without replacing value
// let use `append` function

url.searchParams.set('key', 'value');

console.log(url.search) // <== '?key=value'

// if window.location.href has already some qs params this `set` function
// modify or append key/value in it

For more information about searchParams functions.

URL is not supported in IE, check compatibility

Lymphoma answered 23/5, 2021 at 21:32 Comment(3)
url.searchParams is read-only according to mdn.Ripen
@NicolasAppriou, Ok, is here any code that is against the link you mentioned?Lymphoma
@MuhammedMoussa, Thanks for your great edit, really thanks. but bro, what is IE then?Lymphoma
F
22

/**
* Add a URL parameter 
* @param {string} url 
* @param {string} param the key to set
* @param {string} value 
*/
var addParam = function(url, param, value) {
   param = encodeURIComponent(param);
   var a = document.createElement('a');
   param += (value ? "=" + encodeURIComponent(value) : ""); 
   a.href = url;
   a.search += (a.search ? "&" : "") + param;
   return a.href;
}

/**
* Add a URL parameter (or modify if already exists)
* @param {string} url 
* @param {string} param the key to set
* @param {string} value 
*/
var addOrReplaceParam = function(url, param, value) {
   param = encodeURIComponent(param);
   var r = "([&?]|&amp;)" + param + "\\b(?:=(?:[^&#]*))*";
   var a = document.createElement('a');
   var regex = new RegExp(r);
   var str = param + (value ? "=" + encodeURIComponent(value) : ""); 
   a.href = url;
   var q = a.search.replace(regex, "$1"+str);
   if (q === a.search) {
      a.search += (a.search ? "&" : "") + str;
   } else {
      a.search = q;
   }
   return a.href;
}

url = "http://www.example.com#hashme";
newurl = addParam(url, "ciao", "1");
alert(newurl);

And please note that parameters should be encoded before being appended in query string.

http://jsfiddle.net/48z7z4kx/

Fun answered 22/1, 2013 at 23:29 Comment(11)
Small memory leak - you'll want to remove the anchor element that was added to the document before returning.Clemmer
@freedev, Nope, I'm not sure. ;) I'm having a hard time finding an authoritative source but the evidence suggests that you are correct. Since the created element is never attached to the DOM, it should be cleaned up once the variable goes out of scope. The DOM API isn't particularly well designed when it comes to side effects, so I'm overly cautious.Clemmer
This solution adds a trailing slash to URLs that have no path and reorders parameters, which are unnecessary and possibly undesirable changes. It also appends rather than replacing existing parameters that have no value (e.g. http://abc.def/?a&b&b).Incontinent
@AdamLeggett Thanks for pointing the bug that happens when a request parameter have no value, I have just fixed my answer. The remaining strange behaviors you're talking about, if you're right, are generated by HTML anchor object which usually is a standard browser component. I suggest to double check because very unlikely a browser adds unnecessary or undesirable behaviors.Fun
The browser is appending the trailing slash. You are reordering parameters yourself by appending the desired value at the end every time. This isn't wrong per se, but I'd prefer a solution that doesn't do it. You should also not be matching against &amp;, as this is not a separator; it is part of the value. Beyond that, this solution just does more work and has more code than necessary.Incontinent
Excuse me, &amp; is not part of the value either. It is just an incorrectly encoded query string.Incontinent
@AdamLeggett regarding the &amp; I had few problems with w3c HTML validators and had to use &amp; in place of & when writing URLs in HTML. htmlhelp.com/tools/validator/problems.html#amp #4442094 these problems affected this routine too.Fun
@AdamLeggett A properly written application will find a given query parameter in any order and it shouldn't be order sensitive. Anyway, I have to admit that this solution waste a little of resources manipulating the parameters, so I have just written a new version that it seems to be more efficient. :)Fun
@Fun I agree that an application shouldn't be order sensitive (except the order when a parameter appears multiple times), but my preference is to not modify the order. Anyway, your code could be easily changed to not modify the order. Please see my answer below, it's my attempt to reduce the solution to the smallest code size possible. However, mine modifies the first instance if there are multiple instances.Incontinent
Calling the function multiple times with the same parameter and value will add the parameter multiple times to the url. I added a check, if the url already contains the parameter and value: if (url.indexOf(str) === -1)Ploughman
The purpose of addParam function is indeed add multiple times a parameter, and maybe you should know you can pass same parameter even with same value multiple times. #24060273Fun
H
20

I have a 'class' that does this and here it is:

function QS(){
    this.qs = {};
    var s = location.search.replace( /^\?|#.*$/g, '' );
    if( s ) {
        var qsParts = s.split('&');
        var i, nv;
        for (i = 0; i < qsParts.length; i++) {
            nv = qsParts[i].split('=');
            this.qs[nv[0]] = nv[1];
        }
    }
}

QS.prototype.add = function( name, value ) {
    if( arguments.length == 1 && arguments[0].constructor == Object ) {
        this.addMany( arguments[0] );
        return;
    }
    this.qs[name] = value;
}

QS.prototype.addMany = function( newValues ) {
    for( nv in newValues ) {
        this.qs[nv] = newValues[nv];
    }
}

QS.prototype.remove = function( name ) {
    if( arguments.length == 1 && arguments[0].constructor == Array ) {
        this.removeMany( arguments[0] );
        return;
    }
    delete this.qs[name];
}

QS.prototype.removeMany = function( deleteNames ) {
    var i;
    for( i = 0; i < deleteNames.length; i++ ) {
        delete this.qs[deleteNames[i]];
    }
}

QS.prototype.getQueryString = function() {
    var nv, q = [];
    for( nv in this.qs ) {
        q[q.length] = nv+'='+this.qs[nv];
    }
    return q.join( '&' );
}

QS.prototype.toString = QS.prototype.getQueryString;

//examples
//instantiation
var qs = new QS;
alert( qs );

//add a sinle name/value
qs.add( 'new', 'true' );
alert( qs );

//add multiple key/values
qs.add( { x: 'X', y: 'Y' } );
alert( qs );

//remove single key
qs.remove( 'new' )
alert( qs );

//remove multiple keys
qs.remove( ['x', 'bogus'] )
alert( qs );

I have overridden the toString method so there is no need to call QS::getQueryString, you can use QS::toString or, as I have done in the examples just rely on the object being coerced into a string.

Hey answered 28/1, 2009 at 10:11 Comment(0)
E
16

If you have a string with url that you want to decorate with a param, you could try this oneliner:

urlstring += ( urlstring.match( /[\?]/g ) ? '&' : '?' ) + 'param=value';

This means that ? will be the prefix of the parameter, but if you already have ? in urlstring, than & will be the prefix.

I would also recommend to do encodeURI( paramvariable ) if you didn't hardcoded parameter, but it is inside a paramvariable; or if you have funny characters in it.

See javascript URL Encoding for usage of the encodeURI function.

Extension answered 17/3, 2016 at 17:54 Comment(0)
L
11

This solution updates the window's current URL with updated search parameters without actually reloading the page. This approach is useful in a PWA/SPA context.

function setURLSearchParam(key, value) {
  const url = new URL(window.location.href);
  url.searchParams.set(key, value);
  window.history.pushState({ path: url.href }, '', url.href);
}
Lave answered 20/11, 2021 at 20:35 Comment(1)
this should be marked as the correct answer as its very simple, solves the originally asked question, and does not require the page to be reloadedGuaco
S
9

Sometimes we see ? at the end URL, I found some solutions which generate results as file.php?&foo=bar. I came up with my own solution to work perfectly as I want!

location.origin + location.pathname + location.search + (location.search=='' ? '?' : '&') + 'lang=ar'

Note: location.origin doesn't work in IE, here is its fix.

Sulcate answered 16/4, 2015 at 21:54 Comment(0)
W
9

This is a simple way to add a query parameter:

const query = new URLSearchParams(window.location.search);
query.append("enabled", "true");

And that is it more here.

Please note the support specs.

Wimbush answered 1/8, 2017 at 1:39 Comment(3)
It seems that this is not supported in any version of Internet ExplorerTemekatemerity
Ideal for mobile. When Internet Explorer shows up on my mobile device, I'll throw it away. :-)Todhunter
@Temekatemerity you are right IE/EDGE do not support much. Supported inWimbush
V
8

Following function will help you to add,update and delete parameters to or from URL.

//example1and

var myURL = '/search';

myURL = updateUrl(myURL,'location','california');
console.log('added location...' + myURL);
//added location.../search?location=california

myURL = updateUrl(myURL,'location','new york');
console.log('updated location...' + myURL);
//updated location.../search?location=new%20york

myURL = updateUrl(myURL,'location');
console.log('removed location...' + myURL);
//removed location.../search

//example2

var myURL = '/search?category=mobile';

myURL = updateUrl(myURL,'location','california');
console.log('added location...' + myURL);
//added location.../search?category=mobile&location=california

myURL = updateUrl(myURL,'location','new york');
console.log('updated location...' + myURL);
//updated location.../search?category=mobile&location=new%20york

myURL = updateUrl(myURL,'location');
console.log('removed location...' + myURL);
//removed location.../search?category=mobile

//example3

var myURL = '/search?location=texas';

myURL = updateUrl(myURL,'location','california');
console.log('added location...' + myURL);
//added location.../search?location=california

myURL = updateUrl(myURL,'location','new york');
console.log('updated location...' + myURL);
//updated location.../search?location=new%20york

myURL = updateUrl(myURL,'location');
console.log('removed location...' + myURL);
//removed location.../search

//example4

var myURL = '/search?category=mobile&location=texas';

myURL = updateUrl(myURL,'location','california');
console.log('added location...' + myURL);
//added location.../search?category=mobile&location=california

myURL = updateUrl(myURL,'location','new york');
console.log('updated location...' + myURL);
//updated location.../search?category=mobile&location=new%20york

myURL = updateUrl(myURL,'location');
console.log('removed location...' + myURL);
//removed location.../search?category=mobile

//example5

var myURL = 'https://example.com/search?location=texas#fragment';

myURL = updateUrl(myURL,'location','california');
console.log('added location...' + myURL);
//added location.../search?location=california#fragment

myURL = updateUrl(myURL,'location','new york');
console.log('updated location...' + myURL);
//updated location.../search?location=new%20york#fragment

myURL = updateUrl(myURL,'location');
console.log('removed location...' + myURL);
//removed location.../search#fragment

Here is the function.

function updateUrl(url,key,value){
      if(value!==undefined){
        value = encodeURI(value);
      }
      var hashIndex = url.indexOf("#")|0;
      if (hashIndex === -1) hashIndex = url.length|0;
      var urls = url.substring(0, hashIndex).split('?');
      var baseUrl = urls[0];
      var parameters = '';
      var outPara = {};
      if(urls.length>1){
          parameters = urls[1];
      }
      if(parameters!==''){
        parameters = parameters.split('&');
        for(k in parameters){
          var keyVal = parameters[k];
          keyVal = keyVal.split('=');
          var ekey = keyVal[0];
          var evalue = '';
          if(keyVal.length>1){
              evalue = keyVal[1];
          }
          outPara[ekey] = evalue;
        }
      }

      if(value!==undefined){
        outPara[key] = value;
      }else{
        delete outPara[key];
      }
      parameters = [];
      for(var k in outPara){
        parameters.push(k + '=' + outPara[k]);
      }

      var finalUrl = baseUrl;

      if(parameters.length>0){
        finalUrl += '?' + parameters.join('&'); 
      }

      return finalUrl + url.substring(hashIndex); 
  }
Visible answered 26/5, 2016 at 11:28 Comment(2)
Great thank you so much man this works great :DCox
Wow, this is so long.Sogdian
S
7

This was my own attempt, but I'll use the answer by annakata as it seems much cleaner:

function AddUrlParameter(sourceUrl, parameterName, parameterValue, replaceDuplicates)
{
    if ((sourceUrl == null) || (sourceUrl.length == 0)) sourceUrl = document.location.href;
    var urlParts = sourceUrl.split("?");
    var newQueryString = "";
    if (urlParts.length > 1)
    {
        var parameters = urlParts[1].split("&");
        for (var i=0; (i < parameters.length); i++)
        {
            var parameterParts = parameters[i].split("=");
            if (!(replaceDuplicates && parameterParts[0] == parameterName))
            {
                if (newQueryString == "")
                    newQueryString = "?";
                else
                    newQueryString += "&";
                newQueryString += parameterParts[0] + "=" + parameterParts[1];
            }
        }
    }
    if (newQueryString == "")
        newQueryString = "?";
    else
        newQueryString += "&";
    newQueryString += parameterName + "=" + parameterValue;

    return urlParts[0] + newQueryString;
}

Also, I found this jQuery plugin from another post on stackoverflow, and if you need more flexibility you could use that: http://plugins.jquery.com/project/query-object

I would think the code would be (haven't tested):

return $.query.parse(sourceUrl).set(parameterName, parameterValue).toString();
Swam answered 28/1, 2009 at 10:4 Comment(1)
Thanks for sharing your code, Lessan. I've been using this and it's worked great! I've uploaded a gist of my own version, edited to be slightly more succinct and pass JSHint validation. gist.github.com/jonathanconway/02a183920506acd9890aSubdivide
Y
7

Adding to @Vianney's Answer https://mcmap.net/q/73762/-adding-a-parameter-to-the-url-with-javascript

We can import the Built-in URL module in node as follows

const { URL } = require('url');

Example:

Terminal $ node
> const { URL } = require('url');
undefined
> let url = new URL('', 'http://localhost:1989/v3/orders');
undefined
> url.href
'http://localhost:1989/v3/orders'
> let fetchAll=true, timePeriod = 30, b2b=false;
undefined
> url.href
'http://localhost:1989/v3/orders'
>  url.searchParams.append('fetchAll', fetchAll);
undefined
>  url.searchParams.append('timePeriod', timePeriod);
undefined
>  url.searchParams.append('b2b', b2b);
undefined
> url.href
'http://localhost:1989/v3/orders?fetchAll=true&timePeriod=30&b2b=false'
> url.toString()
'http://localhost:1989/v3/orders?fetchAll=true&timePeriod=30&b2b=false'

Useful Links:

https://developer.mozilla.org/en-US/docs/Web/API/URL https://developer.mozilla.org/en/docs/Web/API/URLSearchParams

Yesman answered 11/3, 2019 at 7:46 Comment(0)
P
6

Check out https://github.com/derek-watson/jsUri

Uri and query string manipulation in javascript.

This project incorporates the excellent parseUri regular expression library by Steven Levithan. You can safely parse URLs of all shapes and sizes, however invalid or hideous.

Physiologist answered 23/5, 2013 at 19:23 Comment(3)
404 - The requested URL /p/jsuri/ was not found on this server. That’s all we know.Tympanum
Looks like it's been moved. I've updated the url. Best of luck!Physiologist
Please include the relevant details in your answer, not just a link.Lanugo
D
6

Try this.

// uses the URL class
function setParam(key, value) {
            let url = new URL(window.document.location);
            let params = new URLSearchParams(url.search.slice(1));

            if (params.has(key)) {
                params.set(key, value);
            }else {
                params.append(key, value);
            }
        }
Discontinuity answered 20/10, 2019 at 8:52 Comment(1)
url.searchParams is the pre-initialized parameter list for that URL object.Underquote
B
6

It handles such URL's:

  • empty
  • doesn't have any parameters
  • already have some parameters
  • have ? at the end, but at the same time doesn't have any parameters

It doesn't handles such URL's:

  • with fragment identifier (i.e. hash, #)
  • if URL already have required query parameter (then there will be duplicate)

Works in:

  • Chrome 32+
  • Firefox 26+
  • Safari 7.1+
function appendQueryParameter(url, name, value) {
    if (url.length === 0) {
        return;
    }

    let rawURL = url;

    // URL with `?` at the end and without query parameters
    // leads to incorrect result.
    if (rawURL.charAt(rawURL.length - 1) === "?") {
        rawURL = rawURL.slice(0, rawURL.length - 1);
    }

    const parsedURL = new URL(rawURL);
    let parameters = parsedURL.search;

    parameters += (parameters.length === 0) ? "?" : "&";
    parameters = (parameters + name + "=" + value);

    return (parsedURL.origin + parsedURL.pathname + parameters);
}

Version with ES6 template strings.

Works in:

  • Chrome 41+
  • Firefox 32+
  • Safari 9.1+
function appendQueryParameter(url, name, value) {
    if (url.length === 0) {
        return;
    }

    let rawURL = url;

    // URL with `?` at the end and without query parameters
    // leads to incorrect result.
    if (rawURL.charAt(rawURL.length - 1) === "?") {
        rawURL = rawURL.slice(0, rawURL.length - 1);
    }

    const parsedURL = new URL(rawURL);
    let parameters = parsedURL.search;

    parameters += (parameters.length === 0) ? "?" : "&";
    parameters = `${parameters}${name}=${value}`;

    return `${parsedURL.origin}${parsedURL.pathname}${parameters}`;
}
Benia answered 15/7, 2020 at 13:55 Comment(1)
updated code which support mutiple params. function insertCustomParams(input) { var output = []; var i = 0; Object.entries(input).forEach(function (k, v) { output[i++] = k.join("="); }); var kvp = document.location.search.substr(1).split("&"); var j = 0; for (; j < kvp.length; j++) { let pair = kvp[j].split("="); if (!Object.keys(input).includes(pair[0])) { output[i++] = pair.join("="); } } document.location.search = output.join("&"); }Unutterable
B
4

Typescript solution:

// get current url query string params
  const urlParams = new URLSearchParams(window.location.search);

// append as there could be other query string params
  urlParams.set("paramKey", "paramValue");

// this will reload the page and set query string params.. 
// ex: http://localhost:3000/dashboard?paramKey=paramValue
  window.location.search = urlParams.toString();
Blevins answered 13/3, 2023 at 7:41 Comment(0)
T
3

Vianney Bajart's answer is correct; however, URL will only work if you have the complete URL with port, host, path and query:

new URL('http://server/myapp.php?id=10&enabled=true')

And URLSearchParams will only work if you pass only the query string:

new URLSearchParams('?id=10&enabled=true')

If you have an incomplete or relative URL and don't care for the base URL, you can just split by ? to get the query string and join later like this:

function setUrlParams(url, key, value) {
  url = url.split('?');
  usp = new URLSearchParams(url[1]);
  usp.set(key, value);
  url[1] = usp.toString();
  return url.join('?');
}

let url = 'myapp.php?id=10';
url = setUrlParams(url, 'enabled', true);  // url = 'myapp.php?id=10&enabled=true'
url = setUrlParams(url, 'id', 11);         // url = 'myapp.php?id=11&enabled=true'

Not compatible with Internet Explorer.

Takeoff answered 28/5, 2018 at 19:42 Comment(2)
If you use var u = new URL(window.location), usp = u.searchParams; you don't have to use any fancy string-splitting.Underquote
While your solution will work for most things, it will mangle the URL if it has a question mark in a parameter value: setUrlParams('https://example.com?foo=thing???&bar=baz', 'baz', 'qux') => "https://example.com?foo=thing&baz=qux???&bar=baz"Underquote
M
3

The following:

  • Merges duplicate query string params
  • Works with absolute and relative URLs
  • Works in the browser and node
/**
 * Adds query params to existing URLs (inc merging duplicates)
 * @param {string} url - src URL to modify
 * @param {object} params - key/value object of params to add
 * @returns {string} modified URL
 */
function addQueryParamsToUrl(url, params) {

    // if URL is relative, we'll need to add a fake base
    var fakeBase = !url.startsWith('http') ? 'http://fake-base.com' : undefined;
    var modifiedUrl = new URL(url || '', fakeBase);

    // add/update params
    Object.keys(params).forEach(function(key) {
        if (modifiedUrl.searchParams.has(key)) {
            modifiedUrl.searchParams.set(key, params[key]);
        }
        else {
            modifiedUrl.searchParams.append(key, params[key]);
        }
    });

    // return as string (remove fake base if present)
    return modifiedUrl.toString().replace(fakeBase, '');
}

Examples:

// returns /guides?tag=api
addQueryParamsToUrl('/guides?tag=hardware', { tag:'api' })

// returns https://orcascan.com/guides?tag=api
addQueryParamsToUrl('https://orcascan.com/guides?tag=hardware', { tag: 'api' })
Maryellen answered 5/1, 2022 at 19:57 Comment(0)
F
2

I like the answer of Mehmet Fatih Yıldız even he did not answer the whole question.

In the same line as his answer, I use this code:

"Its doesn't control parameter existence, and it doesn't change existing value. It adds your parameter to the end"

  /** add a parameter at the end of the URL. Manage '?'/'&', but not the existing parameters.
   *  does escape the value (but not the key)
   */
  function addParameterToURL(_url,_key,_value){
      var param = _key+'='+escape(_value);

      var sep = '&';
      if (_url.indexOf('?') < 0) {
        sep = '?';
      } else {
        var lastChar=_url.slice(-1);
        if (lastChar == '&') sep='';
        if (lastChar == '?') sep='';
      }
      _url += sep + param;

      return _url;
  }

and the tester:

  /*
  function addParameterToURL_TESTER_sub(_url,key,value){
    //log(_url);
    log(addParameterToURL(_url,key,value));
  }

  function addParameterToURL_TESTER(){
    log('-------------------');
    var _url ='www.google.com';
    addParameterToURL_TESTER_sub(_url,'key','value');
    addParameterToURL_TESTER_sub(_url,'key','Text Value');
    _url ='www.google.com?';
    addParameterToURL_TESTER_sub(_url,'key','value');
    _url ='www.google.com?A=B';
    addParameterToURL_TESTER_sub(_url,'key','value');
    _url ='www.google.com?A=B&';
    addParameterToURL_TESTER_sub(_url,'key','value');
    _url ='www.google.com?A=1&B=2';
    addParameterToURL_TESTER_sub(_url,'key','value');

  }//*/
Fancy answered 31/8, 2011 at 10:33 Comment(0)
N
2

I would go with this small but complete library to handle urls in js:

https://github.com/Mikhus/jsurl

Newport answered 2/7, 2013 at 20:33 Comment(1)
Please include the relevant details in your answer, not just a link.Lanugo
T
2

This is what I use when it comes to some basic url param additions or updates on the server-side like Node.js.

CoffeScript:

###
    @method addUrlParam Adds parameter to a given url. If the parameter already exists in the url is being replaced.
    @param {string} url
    @param {string} key Parameter's key
    @param {string} value Parameter's value
    @returns {string} new url containing the parameter
###
addUrlParam = (url, key, value) ->
    newParam = key+"="+value
    result = url.replace(new RegExp('(&|\\?)' + key + '=[^\&|#]*'), '$1' + newParam)
    if result is url
        result = if url.indexOf('?') != -1 then url.split('?')[0] + '?' + newParam + '&' + url.split('?')[1]
    else if url.indexOf('#') != -1 then url.split('#')[0] + '?' + newParam + '#' + url.split('#')[1]
    else url + '?' + newParam
    return result

JavaScript:

function addUrlParam(url, key, value) {
    var newParam = key+"="+value;
    var result = url.replace(new RegExp("(&|\\?)"+key+"=[^\&|#]*"), '$1' + newParam);
    if (result === url) { 
        result = (url.indexOf("?") != -1 ? url.split("?")[0]+"?"+newParam+"&"+url.split("?")[1] 
           : (url.indexOf("#") != -1 ? url.split("#")[0]+"?"+newParam+"#"+ url.split("#")[1] 
              : url+'?'+newParam));
    }
    return result;
}

var url = "http://www.example.com?foo=bar&ciao=3&doom=5#hashme";
result1.innerHTML = addUrlParam(url, "ciao", "1");
<p id="result1"></p>
Theogony answered 6/7, 2015 at 21:57 Comment(0)
C
2

Easiest solution, works if you have already a tag or not, and removes it automatically so it wont keep adding equal tags, have fun

function changeURL(tag)
{
if(window.location.href.indexOf("?") > -1) {
    if(window.location.href.indexOf("&"+tag) > -1){

        var url = window.location.href.replace("&"+tag,"")+"&"+tag;
    }
    else
    {
        var url = window.location.href+"&"+tag;
    }
}else{
    if(window.location.href.indexOf("?"+tag) > -1){

        var url = window.location.href.replace("?"+tag,"")+"?"+tag;
    }
    else
    {
        var url = window.location.href+"?"+tag;
    }
}
  window.location = url;
}

THEN

changeURL("i=updated");
Culley answered 13/7, 2017 at 10:17 Comment(0)
K
2
const params = new URLSearchParams(window.location.search);

params.delete(key)
window.history.replaceState({}, "", decodeURIComponent(`${window.location.pathname}?${params}`));
Kroo answered 6/3, 2022 at 3:44 Comment(0)
B
2

I am adding my solution because it supports relative urls in addition to absolute urls. It is otherwise the same as the top answer which also uses Web API.

/**
 * updates a relative or absolute
 * by setting the search query with
 * the passed key and value.
 */
export const setQueryParam = (url, key, value) => {
  const dummyBaseUrl = 'https://dummy-base-url.com';
  const result = new URL(url, dummyBaseUrl);
  result.searchParams.set(key, value);
  return result.toString().replace(dummyBaseUrl, '');
};

And some jest tests:

// some jest tests
describe('setQueryParams', () => {
  it('sets param on relative url with base path', () => {
    // act
    const actual = setQueryParam(
      '/', 'ref', 'some-value',
    );
    // assert
    expect(actual).toEqual('/?ref=some-value');
  });
  it('sets param on relative url with no path', () => {
    // act
    const actual = setQueryParam(
      '', 'ref', 'some-value',
    );
    // assert
    expect(actual).toEqual('/?ref=some-value');
  });
  it('sets param on relative url with some path', () => {
    // act
    const actual = setQueryParam(
      '/some-path', 'ref', 'some-value',
    );
    // assert
    expect(actual).toEqual('/some-path?ref=some-value');
  });
  it('overwrites existing param', () => {
    // act
    const actual = setQueryParam(
      '/?ref=prev-value', 'ref', 'some-value',
    );
    // assert
    expect(actual).toEqual('/?ref=some-value');
  });
  it('sets param while another param exists', () => {
    // act
    const actual = setQueryParam(
      '/?other-param=other-value', 'ref', 'some-value',
    );
    // assert
    expect(actual).toEqual('/?other-param=other-value&ref=some-value');
  });
  it('honors existing base url', () => {
    // act
    const actual = setQueryParam(
      'https://base.com', 'ref', 'some-value',
    );
    // assert
    expect(actual).toEqual('https://base.com/?ref=some-value');
  });
  it('honors existing base url with some path', () => {
    // act
    const actual = setQueryParam(
      'https://base.com/some-path', 'ref', 'some-value',
    );
    // assert
    expect(actual).toEqual('https://base.com/some-path?ref=some-value');
  });
});

Briney answered 9/3, 2022 at 4:47 Comment(0)
O
1

If you're messing around with urls in links or somewhere else, you may have to take the hash into account as well. Here's a fairly simple to understand solution. Probably not the FASTEST since it uses a regex... but in 99.999% of cases, the difference really doesn't matter!

function addQueryParam( url, key, val ){
    var parts = url.match(/([^?#]+)(\?[^#]*)?(\#.*)?/);
    var url = parts[1];
    var qs = parts[2] || '';
    var hash = parts[3] || '';

    if ( !qs ) {
        return url + '?' + key + '=' + encodeURIComponent( val ) + hash;
    } else {
        var qs_parts = qs.substr(1).split("&");
        var i;
        for (i=0;i<qs_parts.length;i++) {
            var qs_pair = qs_parts[i].split("=");
            if ( qs_pair[0] == key ){
                qs_parts[ i ] = key + '=' + encodeURIComponent( val );
                break;
            }
        }
        if ( i == qs_parts.length ){
            qs_parts.push( key + '=' + encodeURIComponent( val ) );
        }
        return url + '?' + qs_parts.join('&') + hash;
    }
}
Offcenter answered 21/2, 2013 at 19:42 Comment(1)
Not sure why someone downvoted you. This is one of the more reliable solutions, although it's way more code than necessary.Incontinent
B
0

Ok here I compare Two functions, one made by myself (regExp) and another one made by (annakata).

Split array:

function insertParam(key, value)
{
    key = escape(key); value = escape(value);

    var kvp = document.location.search.substr(1).split('&');

    var i=kvp.length; var x; while(i--) 
    {
        x = kvp[i].split('=');

        if (x[0]==key)
        {
                x[1] = value;
                kvp[i] = x.join('=');
                break;
        }
    }

    if(i<0) {kvp[kvp.length] = [key,value].join('=');}

    //this will reload the page, it's likely better to store this until finished
    return "&"+kvp.join('&'); 
}

Regexp method:

function addParameter(param, value)
{
    var regexp = new RegExp("(\\?|\\&)" + param + "\\=([^\\&]*)(\\&|$)");
    if (regexp.test(document.location.search)) 
        return (document.location.search.toString().replace(regexp, function(a, b, c, d)
        {
                return (b + param + "=" + value + d);
        }));
    else 
        return document.location.search+ param + "=" + value;
}

Testing case:

time1=(new Date).getTime();
for (var i=0;i<10000;i++)
{
addParameter("test","test");
}
time2=(new Date).getTime();
for (var i=0;i<10000;i++)
{
insertParam("test","test");
}

time3=(new Date).getTime();

console.log((time2-time1)+" "+(time3-time2));

It seems that even with simplest solution (when regexp use only test and do not enter .replace function) it is still slower than spliting... Well. Regexp is kinda slow but... uhh...

Brenner answered 28/1, 2009 at 12:7 Comment(1)
as I mentioned, this is actually comparatively slow - and fwiw, document.location.search is clearerTraduce
I
0

Here is what I do. Using my editParams() function, you can add, remove, or change any parameter, then use the built in replaceState() function to update the URL:

window.history.replaceState('object or string', 'Title', 'page.html' + editParams('enable', 'true'));


// background functions below:

// add/change/remove URL parameter
// use a value of false to remove parameter
// returns a url-style string
function editParams (key, value) {
  key = encodeURI(key);

  var params = getSearchParameters();

  if (Object.keys(params).length === 0) {
    if (value !== false)
      return '?' + key + '=' + encodeURI(value);
    else
      return '';
  }

  if (value !== false)
    params[key] = encodeURI(value);
  else
    delete params[key];

  if (Object.keys(params).length === 0)
    return '';

  return '?' + $.map(params, function (value, key) {
    return key + '=' + value;
  }).join('&');
}

// Get object/associative array of URL parameters
function getSearchParameters () {
  var prmstr = window.location.search.substr(1);
  return prmstr !== null && prmstr !== "" ? transformToAssocArray(prmstr) : {};
}

// convert parameters from url-style string to associative array
function transformToAssocArray (prmstr) {
  var params = {},
      prmarr = prmstr.split("&");

  for (var i = 0; i < prmarr.length; i++) {
    var tmparr = prmarr[i].split("=");
    params[tmparr[0]] = tmparr[1];
  }
  return params;
}
Indenture answered 18/6, 2014 at 18:13 Comment(0)
T
0

As best I can tell none of the above answers address the case where the query string contains parameters which are themselves an array and hence will appear more than once, e.g:

http://example.com?sizes[]=a&sizes[]=b

The following function is what I wrote to update document.location.search. It takes an array of key/value pair arrays as an argument and it will return a revised version of the latter which you can do whatever you'd like with. I'm using it like this:

var newParams = [
    ['test','123'],
    ['best','456'],
    ['sizes[]','XXL']
];
var newUrl = document.location.pathname + insertParams(newParams);
history.replaceState('', '', newUrl);

If the current url was:

http://example.com/index.php?test=replaceme&sizes[]=XL

This would get you

http://example.com/index.php?test=123&sizes[]=XL&sizes[]=XXL&best=456

Function

function insertParams(params) {
    var result;
    var ii = params.length;
    var queryString = document.location.search.substr(1);
    var kvps = queryString ? queryString.split('&') : [];
    var kvp;
    var skipParams = [];
    var i = kvps.length;
    while (i--) {
        kvp = kvps[i].split('=');
        if (kvp[0].slice(-2) != '[]') {
            var ii = params.length;
            while (ii--) {
                if (params[ii][0] == kvp[0]) {
                    kvp[1] = params[ii][1];
                    kvps[i] = kvp.join('=');
                    skipParams.push(ii);
                }
            }
        }
    }
    var ii = params.length;
    while (ii--) {
        if (skipParams.indexOf(ii) === -1) {
            kvps.push(params[ii].join('='));
        }
    }
    result = kvps.length ? '?' + kvps.join('&') : '';
    return result;
}
Timtima answered 20/1, 2017 at 16:47 Comment(0)
S
0

Try
The regular expressions, so slow, thus:

var SetParamUrl = function(_k, _v) {// replace and add new parameters

    let arrParams = window.location.search !== '' ? decodeURIComponent(window.location.search.substr(1)).split('&').map(_v => _v.split('=')) : Array();
    let index = arrParams.findIndex((_v) => _v[0] === _k); 
    index = index !== -1 ? index : arrParams.length;
    _v === null ? arrParams = arrParams.filter((_v, _i) => _i != index) : arrParams[index] = [_k, _v];
    let _search = encodeURIComponent(arrParams.map(_v => _v.join('=')).join('&'));

    let newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + (arrParams.length > 0 ? '?' +  _search : ''); 

    // window.location = newurl; //reload 

    if (history.pushState) { // without reload  
        window.history.pushState({path:newurl}, null, newurl);
    }

};

var GetParamUrl = function(_k) {// get parameter by key

    let sPageURL = decodeURIComponent(window.location.search.substr(1)),
        sURLVariables = sPageURL.split('&').map(_v => _v.split('='));
    let _result = sURLVariables.find(_v => _v[0] === _k);
    return _result[1];

};

Example:

        // https://some.com/some_path
        GetParamUrl('cat');//undefined
        SetParamUrl('cat', "strData");// https://some.com/some_path?cat=strData
        GetParamUrl('cat');//strData
        SetParamUrl('sotr', "strDataSort");// https://some.com/some_path?cat=strData&sotr=strDataSort
        GetParamUrl('sotr');//strDataSort
        SetParamUrl('cat', "strDataTwo");// https://some.com/some_path?cat=strDataTwo&sotr=strDataSort
        GetParamUrl('cat');//strDataTwo
        //remove param
        SetParamUrl('cat', null);// https://some.com/some_path?sotr=strDataSort
Spinose answered 27/8, 2017 at 17:34 Comment(0)
K
0

With the new achievements in JS here is how one can add query param to the URL:

var protocol = window.location.protocol,
    host = '//' + window.location.host,
    path = window.location.pathname,
    query = window.location.search;

var newUrl = protocol + host + path + query + (query ? '&' : '?') + 'param=1';

window.history.pushState({path:newUrl}, '' , newUrl);

Also see this possibility Moziila URLSearchParams.append()

Kafir answered 2/2, 2018 at 11:14 Comment(0)
A
0

This will work in all modern browsers.

function insertParam(key,value) {
      if (history.pushState) {
          var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?' +key+'='+value;
          window.history.pushState({path:newurl},'',newurl);
      }
    }
Amaranthaceous answered 24/3, 2018 at 12:48 Comment(0)
H
0

Reset all query string

var params = { params1:"val1", params2:"val2" };
let str = jQuery.param(params);

let uri = window.location.href.toString();
if (uri.indexOf("?") > 0)
   uri = uri.substring(0, uri.indexOf("?"));

console.log(uri+"?"+str);
//window.location.href = uri+"?"+str;
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Honky answered 10/7, 2019 at 7:5 Comment(0)
R
-3
var MyApp = new Class();

MyApp.extend({
    utility: {
        queryStringHelper: function (url) {
            var originalUrl = url;
            var newUrl = url;
            var finalUrl;
            var insertParam = function (key, value) {
                key = escape(key);
                value = escape(value);

                //The previous post had the substr strat from 1 in stead of 0!!!
                var kvp = newUrl.substr(0).split('&');

                var i = kvp.length;
                var x;
                while (i--) {
                    x = kvp[i].split('=');

                    if (x[0] == key) {
                        x[1] = value;
                        kvp[i] = x.join('=');
                        break;
                    }
                }

                if (i < 0) {
                    kvp[kvp.length] = [key, value].join('=');
                }

                finalUrl = kvp.join('&');

                return finalUrl;
            };

            this.insertParameterToQueryString = insertParam;

            this.insertParams = function (keyValues) {
                for (var keyValue in keyValues[0]) {
                    var key = keyValue;
                    var value = keyValues[0][keyValue];
                    newUrl = insertParam(key, value);
                }
                return newUrl;
            };

            return this;
        }
    }
});
Ross answered 26/9, 2012 at 20:10 Comment(1)
overcomplicated for this use caseBettyannbettye

© 2022 - 2024 — McMap. All rights reserved.