jquery modify url get parameters

14,206

Solution 1

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

Solution 2

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.

Solution 3

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.

Share:
14,206
Zulakis
Author by

Zulakis

Updated on June 17, 2022

Comments

  • Zulakis
    Zulakis almost 2 years

    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?