41

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
63.9k31 gold badges159 silver badges201 bronze badges
asked Mar 8, 2012 at 17:41
0

12 Answers 12

57

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)

answered Jun 27, 2018 at 9:50

Comments

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

answered Mar 8, 2012 at 17:46

1 Comment

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?
8
//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,1113 gold badges14 silver badges26 bronze badges
answered Sep 10, 2015 at 13:54

2 Comments

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)
(It will also output ?&key=val, in case of only one url param)
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; 
}
answered Nov 20, 2018 at 3:15

2 Comments

Thanks - this made a useful little utility method for me to include on a project, and solved my needs.
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 :)
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);
answered Apr 19, 2013 at 7:33

1 Comment

This library is now called domurl. GitHub is redirecting to the correct repo, just posting here in case that ever changes.
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

answered May 27, 2016 at 3:38

1 Comment

this will only work if you are wanting to refresh the page and you run the risk of an infinite loop.
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);
 }
} 
answered Jan 29, 2022 at 20:47

Comments

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.

answered Jul 2, 2015 at 8:51

Comments

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

answered Nov 27, 2015 at 21:27

Comments

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
answered Mar 22, 2019 at 5:51

Comments

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
 });
})
answered May 12, 2022 at 10:21

Comments

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.8k10 gold badges44 silver badges60 bronze badges
answered Jan 21, 2023 at 2:42

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.