Updating existing URL querystring values with jQuery

前端 未结 9 762
逝去的感伤
逝去的感伤 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

    I like Ali's answer the best. I cleaned up the code into a function and thought I would share it to make someone else's life easier. Hope this helps someone.

    function addParam(currentUrl,key,val) {
        var url = new URL(currentUrl);
        url.searchParams.set(key, val);
        return url.href; 
    }
    
    0 讨论(0)
  • 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 :)

    0 讨论(0)
  • 2020-12-01 16:56

    You could do something like this:

    // If key exists updates the value
    if (location.href.indexOf('key=') > -1) {
        location.href = location.href.replace('key=current_val', 'key=new_val');
    
    // If not, append
    } else {
         location.href = location.href + '&key=new_val';
    }
    

    Regards

    0 讨论(0)
提交回复
热议问题