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:
The value of a parameter can be updated with the set() method of URLSearchParams object. After setting the new value you can get the new query string with the toString() method. This query string can be set as the new value of the search property of the URL object.
This can be done by using the java. net. URI class to construct a new instance using the parts from an existing one, this should ensure it conforms to URI syntax. The query part will either be null or an existing string, so you can decide to append another parameter with & or start a new query.
set('PARAM_HERE', VALUE_HERE); history. pushState(null, '', url); This will preserve everything about the URL and only change or add the one query param. You can also use replaceState instead of pushState if you don't want it to create a new browser history entry.
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)
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With