39

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
0

12 Answers 12

55

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)

0
19

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

1
  • 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
    Commented Apr 7, 2017 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; 
}
2
  • Thanks - this made a useful little utility method for me to include on a project, and solved my needs. Commented Aug 14, 2019 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 :) Commented Mar 31, 2021 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);
}
2
  • 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
    Commented Jan 18, 2017 at 18:39
  • (It will also output ?&key=val, in case of only one url param)
    – leo
    Commented Jan 18, 2017 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);
1
  • 1
    This library is now called domurl. GitHub is redirecting to the correct repo, just posting here in case that ever changes.
    – vaindil
    Commented Apr 14, 2017 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

1
  • this will only work if you are wanting to refresh the page and you run the risk of an infinite loop.
    – tdbeckett
    Commented Sep 12, 2019 at 21:54
1

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);
    }
} 
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.

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 :)

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
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
  });
})
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); 
}

Your Answer

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

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