jquery modify url get parameters

2020-06-20 19:17发布

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?

8条回答
贪生不怕死
2楼-- · 2020-06-20 19:32

location.href = location.origin+location.pathname+location.search;

Replace location.search by your new arguments like "?foo=bar&tic=tac"

查看更多
贼婆χ
3楼-- · 2020-06-20 19:34

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

查看更多
Luminary・发光体
4楼-- · 2020-06-20 19:38

Set or Update a URL/QueryString Parameter, and update URL using HTML history.replaceState()

You can try something like this:

var updateQueryStringParam = function (key, value) {
    var baseUrl = [location.protocol, '//', location.host, location.pathname].join(''),
        urlQueryString = document.location.search,
        newParam = key + '=' + value,
        params = '?' + newParam;

    // If the "search" string exists, then build params from it
    if (urlQueryString) {
        keyRegex = new RegExp('([\?&])' + key + '[^&]*');

        // If param exists already, update it
        if (urlQueryString.match(keyRegex) !== null) {
            params = urlQueryString.replace(keyRegex, "$1" + newParam);
        } else { // Otherwise, add it to end of query string
            params = urlQueryString + '&' + newParam;
        }
    }
    window.history.replaceState({}, "", baseUrl + params);
};
查看更多
Lonely孤独者°
5楼-- · 2020-06-20 19:41

Since your parameter can be at any place. So this will work fine

url="http://google.de/test.php?a=b&c=d&e=f";
url=url.replace(/&c=.*&/,"&c=h&")
查看更多
看我几分像从前
6楼-- · 2020-06-20 19:43

I've put together a really simple method but it will only work with what you're trying to achieve:

var url = 'http://google.de/test.php?a=b&c=d&e=f';
var gets =  url.split('.php?');
var ge = gets[1].split('&');
var change = ge[1].split('=');
var change[1] = 'h';
var newUrl = url[0] + '.php?' + ge[0] + '&' + change[0] + '=' + change[1] + '&' + ge[2];
查看更多
相关推荐>>
7楼-- · 2020-06-20 19:50

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.

查看更多
登录 后发表回答