Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
114
rated 0 times [  117] [ 3]  / answers: 1 / hits: 83686  / 12 Years ago, thu, march 8, 2012, 12:00:00

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


More From » jquery

 Answers
131

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




[#86976] Wednesday, March 7, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
karivictoriab

Total Points: 530
Total Questions: 90
Total Answers: 95

Location: Honduras
Member since Sun, Dec 26, 2021
2 Years ago
;