Adding a parameter to the URL with JavaScript

后端 未结 30 2233
刺人心
刺人心 2020-11-22 07:33

In a web application that makes use of AJAX calls, I need to submit a request but add a parameter to the end of the URL, for example:

Original URL:

相关标签:
30条回答
  • 2020-11-22 08:09

    If you're messing around with urls in links or somewhere else, you may have to take the hash into account as well. Here's a fairly simple to understand solution. Probably not the FASTEST since it uses a regex... but in 99.999% of cases, the difference really doesn't matter!

    function addQueryParam( url, key, val ){
        var parts = url.match(/([^?#]+)(\?[^#]*)?(\#.*)?/);
        var url = parts[1];
        var qs = parts[2] || '';
        var hash = parts[3] || '';
    
        if ( !qs ) {
            return url + '?' + key + '=' + encodeURIComponent( val ) + hash;
        } else {
            var qs_parts = qs.substr(1).split("&");
            var i;
            for (i=0;i<qs_parts.length;i++) {
                var qs_pair = qs_parts[i].split("=");
                if ( qs_pair[0] == key ){
                    qs_parts[ i ] = key + '=' + encodeURIComponent( val );
                    break;
                }
            }
            if ( i == qs_parts.length ){
                qs_parts.push( key + '=' + encodeURIComponent( val ) );
            }
            return url + '?' + qs_parts.join('&') + hash;
        }
    }
    
    0 讨论(0)
  • 2020-11-22 08:11

    This is a simple way to add a query parameter:

    const query = new URLSearchParams(window.location.search);
    query.append("enabled", "true");
    

    And that is it more here.

    Please note the support specs.

    0 讨论(0)
  • 2020-11-22 08:13

    This will work in all modern browsers.

    function insertParam(key,value) {
          if (history.pushState) {
              var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?' +key+'='+value;
              window.history.pushState({path:newurl},'',newurl);
          }
        }
    
    0 讨论(0)
  • 2020-11-22 08:14

    A basic implementation which you'll need to adapt would look something like this:

    function insertParam(key, value) {
        key = encodeURIComponent(key);
        value = encodeURIComponent(value);
    
        // kvp looks like ['key1=value1', 'key2=value2', ...]
        var kvp = document.location.search.substr(1).split('&');
        let i=0;
    
        for(; i<kvp.length; i++){
            if (kvp[i].startsWith(key + '=')) {
                let pair = kvp[i].split('=');
                pair[1] = value;
                kvp[i] = pair.join('=');
                break;
            }
        }
    
        if(i >= kvp.length){
            kvp[kvp.length] = [key,value].join('=');
        }
    
        // can return this or...
        let params = kvp.join('&');
    
        // reload page with new params
        document.location.search = params;
    }
    

    This is approximately twice as fast as a regex or search based solution, but that depends completely on the length of the querystring and the index of any match


    the slow regex method I benchmarked against for completions sake (approx +150% slower)

    function insertParam2(key,value)
    {
        key = encodeURIComponent(key); value = encodeURIComponent(value);
    
        var s = document.location.search;
        var kvp = key+"="+value;
    
        var r = new RegExp("(&|\\?)"+key+"=[^\&]*");
    
        s = s.replace(r,"$1"+kvp);
    
        if(!RegExp.$1) {s += (s.length>0 ? '&' : '?') + kvp;};
    
        //again, do what you will here
        document.location.search = s;
    }
    
    0 讨论(0)
  • 2020-11-22 08:14
    const urlParams = new URLSearchParams(window.location.search);
    
    urlParams.set('order', 'date');
    
    window.location.search = urlParams;
    

    .set first agrument is the key, the second one is the value.

    0 讨论(0)
  • 2020-11-22 08:15

    As best I can tell none of the above answers address the case where the query string contains parameters which are themselves an array and hence will appear more than once, e.g:

    http://example.com?sizes[]=a&sizes[]=b
    

    The following function is what I wrote to update document.location.search. It takes an array of key/value pair arrays as an argument and it will return a revised version of the latter which you can do whatever you'd like with. I'm using it like this:

    var newParams = [
        ['test','123'],
        ['best','456'],
        ['sizes[]','XXL']
    ];
    var newUrl = document.location.pathname + insertParams(newParams);
    history.replaceState('', '', newUrl);
    

    If the current url was:

    http://example.com/index.php?test=replaceme&sizes[]=XL

    This would get you

    http://example.com/index.php?test=123&sizes[]=XL&sizes[]=XXL&best=456

    Function

    function insertParams(params) {
        var result;
        var ii = params.length;
        var queryString = document.location.search.substr(1);
        var kvps = queryString ? queryString.split('&') : [];
        var kvp;
        var skipParams = [];
        var i = kvps.length;
        while (i--) {
            kvp = kvps[i].split('=');
            if (kvp[0].slice(-2) != '[]') {
                var ii = params.length;
                while (ii--) {
                    if (params[ii][0] == kvp[0]) {
                        kvp[1] = params[ii][1];
                        kvps[i] = kvp.join('=');
                        skipParams.push(ii);
                    }
                }
            }
        }
        var ii = params.length;
        while (ii--) {
            if (skipParams.indexOf(ii) === -1) {
                kvps.push(params[ii].join('='));
            }
        }
        result = kvps.length ? '?' + kvps.join('&') : '';
        return result;
    }
    
    0 讨论(0)
提交回复
热议问题