34

Let's say I have a url such as:

http://www.example.com/hello.png?w=100&h=100&bg=white

What I'd like to do is update the values of the w and h querystring, but leave the bg querystring intact, for example:

http://www.example.com/hello.png?w=200&h=200&bg=white

So what's the fastest most efficient way to read the querystring values (and they could be any set of querystring values, not just w, h, and bg), update a few or none of the values, and return the full url with the new querystring?

So:

  1. Get the values of each querystring key
  2. Update any number of the keys
  3. Rebuild the url with the new values
  4. Keep all of the other values which weren't updated
  5. It will not have a standard set of known keys, it could change per URL
rid
  • 61,078
  • 31
  • 152
  • 193
adam
  • 3,498
  • 6
  • 34
  • 46

12 Answers12

48

Simple solution

You can use URLSearchParams.set() like below:

var currentUrl = 'http://www.example.com/hello.png?w=100&h=100&bg=white';
var url = new URL(currentUrl);
url.searchParams.set("w", "200"); // setting your param
var newUrl = url.href; 
console.log(newUrl);

Online demo (jsfiddle)

Ali Soltani
  • 9,589
  • 5
  • 30
  • 55
18

Get query string values this way and use $.param to rebuild query string

UPDATE:

This is an example, also check fiddle:

  function getQueryVariable(url, variable) {
    var query = url.substring(1);
     var vars = query.split('&');
     for (var i=0; i<vars.length; i++) {
          var pair = vars[i].split('=');
          if (pair[0] == variable) {
            return pair[1];
          }
     }

     return false;
  }

  var url = 'http://www.example.com/hello.png?w=100&h=100&bg=white';
       
  var w = getQueryVariable(url, 'w');
  var h = getQueryVariable(url, 'h');
  var bg = getQueryVariable(url, 'bg');

  // http://www.example.com/hello.png?w=200&h=200&bg=white
  var params = { 'w':200, 'h':200, 'bg':bg };
  var new_url = 'http://www.example.com/hello.png?' + jQuery.param(params);

You can change the function to use current url:

  function getQueryVariable(variable) {
    var query = window.location.search.substring(1);
     var vars = query.split('&');
     for (var i=0; i<vars.length; i++) {
          var pair = vars[i].split('=');
          if (pair[0] == variable) {
            return pair[1];
          }
     }

     return false;
  }
Community
  • 1
  • 1
dotoree
  • 2,983
  • 1
  • 24
  • 29
  • what if we need to update just some of the variables and we have a lot of variables in url that we are not going to update? – Ahmed Ali Apr 07 '17 at 19:02
8

I like Ali's answer the best. I cleaned up the code into a function and thought I would share it to make someone else's life easier. Hope this helps someone.

function addParam(currentUrl,key,val) {
    var url = new URL(currentUrl);
    url.searchParams.set(key, val);
    return url.href; 
}
user1254723
  • 181
  • 1
  • 8
  • Thanks - this made a useful little utility method for me to include on a project, and solved my needs. – FullMetalEngineer Aug 14 '19 at 21:02
  • I'm new to this, do you have an example? I'm trying to get my event title into a hidden field my form. My form can get parameter from url, but i can't convert the title into a parameter.... And i don't know if this is the best way at all :) – Keviin Cosmos Mar 31 '21 at 21:39
7
//update URL Parameter
function updateURL(key,val){
    var url = window.location.href;
    var reExp = new RegExp("[\?|\&]"+key + "=[0-9a-zA-Z\_\+\-\|\.\,\;]*");

    if(reExp.test(url)) {
        // update
        var reExp = new RegExp("[\?&]" + key + "=([^&#]*)");
        var delimiter = reExp.exec(url)[0].charAt(0);
        url = url.replace(reExp, delimiter + key + "=" + val);
    } else {
        // add
        var newParam = key + "=" + val;
        if(!url.indexOf('?')){url += '?';}

        if(url.indexOf('#') > -1){
            var urlparts = url.split('#');
            url = urlparts[0] +  "&" + newParam +  (urlparts[1] ?  "#" +urlparts[1] : '');
        } else {
            url += "&" + newParam;
        }
    }
    window.history.pushState(null, document.title, url);
}
Pixel Rubble
  • 1,104
  • 3
  • 14
  • 26
hitchhikers
  • 81
  • 1
  • 1
  • 1
    This is a convenient function, but it will not work if the url has no query params from the start, but hash a '#'. You can fix this by changing the indexOf line to `(url.indexOf('?') === -1)` – leo Jan 18 '17 at 18:39
  • (It will also output `?&key=val`, in case of only one url param) – leo Jan 18 '17 at 18:39
3

Another way (independent of jQuery or other libraries): https://github.com/Mikhus/jsurl

var u = new Url;
// or
var u = new Url('/some/path?foo=baz');
alert(u);
u.query.foo = 'bar';
alert(u);
Mikhus
  • 1,069
  • 11
  • 8
  • 1
    This library is now called [domurl](https://github.com/Mikhus/domurl). GitHub is redirecting to the correct repo, just posting here in case that ever changes. – vaindil Apr 14 '17 at 14:04
1

You could do something like this:

// If key exists updates the value
if (location.href.indexOf('key=') > -1) {
    location.href = location.href.replace('key=current_val', 'key=new_val');

// If not, append
} else {
     location.href = location.href + '&key=new_val';
}

Regards

Nicolas Finelli
  • 2,170
  • 1
  • 14
  • 9
0

My URL is like this: http://localhost/dentistryindia/admin/hospital/add_procedure?hid=241&hpr_id=12

var reExp = /hpr_id=\\d+/;
var url = window.location.href;
url = url.toString(); 
var hrpid = $("#category :selected").val(); //new value to replace hpr_id
var reExp = new RegExp("[\\?&]" + 'hpr_id' + "=([^&#]*)"),
delimeter = reExp.exec(url)[0].charAt(0),
newUrl = url.replace(reExp, delimeter + 'hpr_id' + "=" + hrpid);
window.location.href = newUrl;

This is how it worked for me.

chandoo
  • 1,276
  • 2
  • 21
  • 32
0

Another way you you can do this, using some simple reg ex code by Samuel Santos here like this:

/*
 * queryParameters -> handles the query string parameters
 * queryString -> the query string without the fist '?' character
 * re -> the regular expression
 * m -> holds the string matching the regular expression
 */
var queryParameters = {}, queryString = location.search.substring(1),
        re = /([^&=]+)=([^&]*)/g, m;

// Creates a map with the query string parameters
while (m = re.exec(queryString)) {
    queryParameters[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
}

// Update w and h
queryParameters['w'] = 200;
queryParameters['h'] = 200;

Now you can either create a new URL:

var url = window.location.protocol + '//' + window.location.hostname + window.location.pathname;

// Build new Query String
var params = $.param(queryParameters);
if (params != '') {
    url = url + '?' + params;
}

OR you could just use the params to cause browser to reload right away:

location.search = params;

OR do whatever you want with :)

PanPipes
  • 4,584
  • 1
  • 17
  • 24
0

URI.js seems like the best approach to me http://medialize.github.io/URI.js/

let uri = URI("http://test.com/foo.html").addQuery("a", "b");
// http://test.com/foo.html?a=b
uri.addQuery("c", 22);
// http://test.com/foo.html?a=b&c=22
uri.hash("h1");
// http://test.com/foo.html?a=b&c=22#h1
uri.hash("h2");
// http://test.com/foo.html?a=b&c=22#h2
vinnyjames
  • 2,040
  • 18
  • 26
0

Alright, If you are someone like me who only wants to update query string on URL without reloading the page. try following code

updateQueryString('id',post.id)

function updateQueryString(key, value) {
    if (history.pushState) {
        let searchParams = new URLSearchParams(window.location.search);
        searchParams.set(key, value);
        let newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?' + searchParams.toString();
        window.history.pushState({path: newurl}, '', newurl);
    }
} 
Kunal Rajput
  • 664
  • 1
  • 7
  • 21
0
$('.desktopsortpriceHandler').on('change', function(){
  let price_id = $(this).val()
  $('.btn_product_locality_filter').attr("href", function (i, val) {
    //  if p is in between of url 
    val = val.replace(/p=.*?&/i, ""); ----> this will help to get the parameter using regex and replace it with ""
    //  if p at the end of url 
    val = val.replace(/&p=.*?$/i, ""); ----> this will help to get the parameter using regex and replace it with ""
    return val + `&p=${encodeURIComponent(price_id.toString())}`;   ---> then you can add it back as parameter with new value
  });
})
sandeepnegi
  • 123
  • 13
0

i'm using this

function UpdateUrl(a,b,c,pagetitle) { 
    var url = window.location.href;
    var usplit = url.split("?");
    var uObj = { Title: pagetitle, Url: usplit[0] + "?w=a&h=b&bg=c};
    history.pushState(uObj, uObj.Title, uObj.Url); 
}
Syscall
  • 19,327
  • 10
  • 37
  • 52
kamal.shalabe
  • 101
  • 1
  • 5