I got a URL like this:
http://google.de/test.php?a=b&c=d&e=f
I know got to modify just one of the GET params like this: (c
is "h" instead of "d")
http://google.de/test.php?a=b&c=h&e=f
and redirect to the new url. All other GET params should stay the same.
How am I going to do this?
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.
Method 2: Adding a new state with pushState() Method: The pushState() method is used to add a new history entry with the properties passed as parameters. This will change the current URL to the new state given without reloading the page.
Any word after the question mark (?) in a URL is considered to be a parameter which can hold values. The value for the corresponding parameter is given after the symbol "equals" (=). Multiple parameters can be passed through the URL by separating them with multiple "&".
I agree its best to use a library for this purpose as mentioned in other answers.
However, here is a string replacement solution based on regular expressions if you need a simpler quick fix.
var url = "http://my.com/page?x=y&z=1&w=34";
var regEx = /([?&]z)=([^#&]*)/g;
var newurl = url.replace(regEx, '$1=newValue');
Here I'm replacing the query string key 'z' with 'newVlaue'
Have a look at this fiddle: http://jsfiddle.net/BuddhiP/PkNsx
A little known feature of PHP is that a latter naming of an existing parameter overrides the earlier.
With this knowledge at hand, you can just do the following:
location.href = location.href + '&c=h';
Easy.
as mentioned window.location.search
will give you the query string with ?
included.
I would then turn these into an object (perhaps with a library like http://github.com/medialize/URI.js) to make it easier to work with the params.
like var params = { key: value, key1: value1}
You could then modify the value you wanted and convert your key value pairs back to a query string.
After this you could use window.location
to move the user to next page.
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