Adding a parameter to the URL with JavaScript

后端 未结 30 2283
刺人心
刺人心 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: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){
            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;
    }
    

提交回复
热议问题