Updating existing URL querystring values with jQuery

前端 未结 9 866
逝去的感伤
逝去的感伤 2020-12-01 16:15

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

9条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-01 16:55

    Another way you you can do this, using some simple reg ex code by Samuel Santos here like this:

    /*
     * queryParameters -> handles the query string parameters
     * queryString -> the query string without the fist '?' character
     * re -> the regular expression
     * m -> holds the string matching the regular expression
     */
    var queryParameters = {}, queryString = location.search.substring(1),
            re = /([^&=]+)=([^&]*)/g, m;
    
    // Creates a map with the query string parameters
    while (m = re.exec(queryString)) {
        queryParameters[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
    }
    
    // Update w and h
    queryParameters['w'] = 200;
    queryParameters['h'] = 200;
    

    Now you can either create a new URL:

    var url = window.location.protocol + '//' + window.location.hostname + window.location.pathname;
    
    // Build new Query String
    var params = $.param(queryParameters);
    if (params != '') {
        url = url + '?' + params;
    }
    

    OR you could just use the params to cause browser to reload right away:

    location.search = params;
    

    OR do whatever you want with :)

提交回复
热议问题