Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery modify url get parameters

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?

like image 969
Zulakis Avatar asked Nov 25 '12 14:11

Zulakis


People also ask

How can the parameters in a URL be edited?

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.

How do I change URL without reloading?

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.

How do you add a parameter to a URL?

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 "&".


3 Answers

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

like image 184
BuddhiP Avatar answered Oct 19 '22 23:10

BuddhiP


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.

like image 44
Christian Avatar answered Oct 19 '22 23:10

Christian


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.

like image 29
dm03514 Avatar answered Oct 19 '22 22:10

dm03514